简体   繁体   English

是否可以在一个表中创建两个主键?

[英]Is it possible to make two primary keys in one table?

Hi I want to know if it is possible to make two primary keys in one table in MySQL. 嗨,我想知道是否有可能在MySQL的一个表中创建两个主键。 If so, please explain the concept behind this. 如果是这样,请解释其背后的概念。 I am asking because I have seen a table in which two primary keys are there with no auto increment set. 我问是因为我看过一个表,其中有两个没有设置自动增量的主键。

you can only have 1 primary key, but: 您只能有1个主键,但是:

  • you can combine more than one column to be the primary key (maybe it's this what you have seen) 您可以将多个列组合为主键(也许就是您所看到的)
  • the primary key don't needs to be an auto-increment, it just has to be unique 主键不需要是自动增量,它必须是唯一的
  • you can add more than one index to one or more colums to speed up SELECT-statements (but slow down INSERT / UPDATE) 您可以向一个或多个列添加多个索引以加快SELECT语句的速度(但会降低INSERT / UPDATE的速度)
  • those indexes can be marked as unique, wich means they don't let you insert a second row with the same content in the index-fields (just like a primary key) 这些索引可以标记为唯一,这意味着它们不允许您在索引字段中插入内容相同的第二行(就像主键一样)

http://dev.mysql.com/doc/refman/5.1/en/create-table.html http://dev.mysql.com/doc/refman/5.1/en/create-table.html

[...] A table can have only one PRIMARY KEY. [...]一个表只能有一个PRIMARY KEY。 [...] [...]

No, but you can have other UNIQUE indexes on the table, in addition to the PRIMARY KEY. 否,但是除了PRIMARY KEY,您还可以在表上拥有其他UNIQUE索引。 UNIQUE + NOT NULL is basically the same as a primary key. UNIQUE + NOT NULL与主键基本相同。

What you have seen is probably a composite primary key (more than one column making up the unique key). 您所看到的可能是一个复合主键(由多个列组成唯一键)。

Use a Composite Primary Key... 使用复合主键...

eg 例如

CREATE TABLE table1 ( 
   first_id int unsigned not null, 
   second_id int unsigned not null auto_increment, 
   user_id int unsigned not null, 
   desc text not null, 
PRIMARY KEY(first_id, second_id));

Also, check out the example here 另外,在这里查看示例

You can use multiple columns for your primary key in this way: 您可以通过以下方式将多列用作主键:

CREATE TABLE
    newTable
    ( field1 INT(11)
    , field2 INT(11)
    , field3 VARCHAR(5)
    , field4 BLOB
    , PRIMARY KEY (field2, field1, field3)   <====
    )

A table can have a single PRIMARY key, which may consist of one or more columns. 一个表可以具有单个PRIMARY键,该键可以由一个或多个列组成。 A table can also have a number of additional keys defined on it, as UNIQUE KEY constraints. 一个表还可以在其上定义许多其他键,作为UNIQUE KEY约束。

It's not clear from your description whether you were looking at a table with multiple keys defined, or a table with a multi-column PRIMARY KEY. 从您的描述中不清楚是要查看定义了多个键的表,还是要查看具有多列PRIMARY KEY的表。

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

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