简体   繁体   English

如何更改表以使字段组合成为MySQL中的主键?

[英]How to alter a table to make a combination of fields as the primary key in MySQL?

I created a table named mytable1 in MySQL with 4 fields namely col1, col2, col3, col4,. 我在MySQL中创建了一个名为mytable1的表,其中包含4个字段,分别为col1,col2,col3,col4。 Initially while creating the table I made col1 the primary key. 最初,在创建表时,我将col1作为主键。 But now I need to make the combination of (col1, col2,col3) as the primary key as col1's value need to repeat in my table. 但是现在我需要将(col1,col2,col3)的组合作为主键,因为col1的值需要在表中重复。

Please help. 请帮忙。

ALTER TABLE mytable1 DROP PRIMARY KEY, ADD PRIMARY KEY(col1, col2, col3);

You need to drop first the primary since you can only have one primary in a table and add it again. 您需要先删除主数据库,因为表中只能有一个主数据库,然后再次添加它。 This can be done in a single line, 这可以单行完成,

ALTER TABLE  tableName DROP PRIMARY KEY, ADD PRIMARY KEY (col1, col2, col3)
ALTER TABLE mytable1
    DROP PRIMARY KEY,
    ADD PRIMARY KEY (col1, col2, col3);

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

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