我有一个包含两个int值的表,它们是id.这些ID本身可以在表中显示任意次数,但它们一起应该只出现一次.
Is there a way to make a pair of values unique and still allow the individual values to show up multiple times?
作为跟进,如果可能的话,这对值可以用作键吗?我目前有一个第三列,用于为我的密钥提供唯一的自动增量值.
我有一个包含两个int值的表,它们是id.这些ID本身可以在表中显示任意次数,但它们一起应该只出现一次.
Is there a way to make a pair of values unique and still allow the individual values to show up multiple times?
作为跟进,如果可能的话,这对值可以用作键吗?我目前有一个第三列,用于为我的密钥提供唯一的自动增量值.
这叫做复合密钥.
如果你想把你的实际PK改成复合PK,使用
Alter table <your table> drop PRIMARY KEY;
Alter table <your table> drop COLUMN <your autoincremented column>;
Alter table <your table> add [constraint <constraint name>] PRIMARY KEY (<col1>, <col2>);
你也可以只添加一个唯一的约束(你的PK将是相同的,唯一对…必须是唯一的).
alter table <your table> add [constraint <constraint name>] unique index(<col1>, <col2>);
就个人而言,我会推荐第二种解决方案(简单PK+唯一约束),但这只是个人观点.你可以在谷歌上搜索关于复合键的利弊争论.
[]
之间的部分是可选的.
EDIT
如果要在create table语句中执行此操作
对于复合pk
CREATE TABLE Test(
id1 int NOT NULL,
id2 int NOT NULL,
id3 int NOT NULL,
PRIMARY KEY (id1, id2)
);
对于唯一索引
CREATE TABLE Test1(
id1 int NOT NULL AUTO_INCREMENT,
id2 int NOT NULL,
id3 int NOT NULL,
PRIMARY KEY (id1),
UNIQUE KEY (id2, id3)
);