开发者

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. 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:

  • 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)
  • 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

[...] A table can have only one PRIMARY KEY. [...]


No, but you can have other UNIQUE indexes on the table, in addition to the PRIMARY KEY. UNIQUE + NOT NULL is basically the same as a primary key.

What you have seen is probably a composite primary key (more than one column making up the unique key).


Use a Composite Primary Key...

e.g.

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. A table can also have a number of additional keys defined on it, as UNIQUE KEY constraints.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜