简体   繁体   English

使用复合主键自动增量

[英]Auto increment with composite primary key

I am not entirely sure what to search so I apologize if this is in fact a duplicate. 我不完全确定要搜索什么,所以我很抱歉,如果这实际上是重复的。

I have a table (or at least would like to) as follows: 我有一张桌子(或至少想要)如下:

  • ID ID
  • Company Name 公司名
  • SomeOtherInfo SomeOtherInfo

The primary key would be ID and Company name (composite primary key). 主键是IDCompany name (复合主键)。 What I would like is so that the ID auto increments on each company. 我想要的是每个公司的ID自动递增。

Ex: 例如:

1-google
2-google
3-google
1-yahoo
4-google
2-yahoo

This way they are always unique, but each one increments for each company individually. 通过这种方式,它们始终是唯一的,但每个公司单独递增。

Is this possible from simple SQL create commands, would rather not have 2 tables and join them using a secondary ID. 这可能来自简单的SQL创建命令,而不是没有2个表并使用辅助ID连接它们。

Let me know, thanks. 让我知道,谢谢。

If I follow the question. 如果我按照这个问题。 Create a single table with an identity on the ID column. 在ID列上创建一个带有标识的表。 Then create a unique index on the Company Name. 然后在公司名称上创建唯一索引。

MySql Version MySql版本
 CREATE TABLE Company ( CompanyID int NOT NULL AUTO_INCREMENT, CompanyName varchar(255) NOT NULL, OtherData varchar(255), PRIMARY KEY (CompanyID) ); CREATE UNIQUE INDEX CompanyUniqueComposite ON Company (CompanyID , CompanyName ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM