MySQL - 使一对值唯一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12763726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - Make a pair of values unique
提问by Josh Brittain
I have a table with two int values that are IDs. On their own these IDs can show up any number of times in the table, but together they should only ever appear once.
我有一个表,其中包含两个作为 ID 的 int 值。这些 ID 本身可以在表中出现任意次数,但它们一起应该只出现一次。
Is there a way to make a pair of values unique and still allow the individual values to show up multiple times?
有没有办法使一对值唯一并且仍然允许单个值出现多次?
As a follow up, if this is possible can the pair of values be used as a key? I currently have a 3rd column for a unique auto increment value for my key.
作为跟进,如果可能的话,这对值可以用作键吗?我目前有一个第三列,用于我的密钥的唯一自动增量值。
回答by Rapha?l Althaus
It's called a composite key.
它被称为复合键。
If you want to change your actual PK to a composite one, use
如果要将实际 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>);
You can also just add a unique constraint (your PK will be the same, and unique pairs... will have to be unique).
您也可以只添加一个唯一约束(您的 PK 将是相同的,并且唯一的对......必须是唯一的)。
alter table <your table> add [constraint <constraint name>] unique index(<col1>, <col2>);
Personnally, I would recommend the second solution (simple PK + unique constraint), but that's just a personal point of view. You can google for pros and cons arguments about composite keys.
就我个人而言,我会推荐第二种解决方案(简单的 PK + 唯一约束),但这只是个人观点。您可以在 google 上搜索有关复合键的优缺点参数。
The part between []
are optional.
之间的部分[]
是可选的。
EDIT
编辑
If you wanna do this in the create table statement
如果您想在 create table 语句中执行此操作
For a composite pk
对于复合 pk
CREATE TABLE Test(
id1 int NOT NULL,
id2 int NOT NULL,
id3 int NOT NULL,
PRIMARY KEY (id1, id2)
);
For an unique index
对于唯一索引
CREATE TABLE Test1(
id1 int NOT NULL AUTO_INCREMENT,
id2 int NOT NULL,
id3 int NOT NULL,
PRIMARY KEY (id1),
UNIQUE KEY (id2, id3)
);
回答by Przemek Lewandowski
Try this: ALTER TABLE table_name ADD CONSTRAINT uc_name UNIQUE (col1,col2)
尝试这个: ALTER TABLE table_name ADD CONSTRAINT uc_name UNIQUE (col1,col2)
回答by jspcal
add primary key (col1, col2)
to your create table definition
添加primary key (col1, col2)
到您的创建表定义