SQL 在 Postgresql 中,在两列的组合上强制唯一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14221775/
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
In Postgresql, force unique on combination of two columns
提问by PearsonArtPhoto
I would like to set up a table in PostgreSQL such that two columns together must be unique. There can be multiple values of either value, so long as there are not two that share both.
我想在 PostgreSQL 中设置一个表,以便两列一起必须是唯一的。任何一个值都可以有多个值,只要没有两个共享这两个值即可。
For instance:
例如:
CREATE TABLE someTable (
id int PRIMARY KEY AUTOINCREMENT,
col1 int NOT NULL,
col2 int NOT NULL
)
So, col1
and col2
can repeat, but not at the same time. So, this would be allowed (Not including the id)
所以,col1
并且col2
可以重复,但不能同时重复。所以,这将被允许(不包括 id)
1 1
1 2
2 1
2 2
but not this:
但不是这个:
1 1
1 2
1 1 -- would reject this insert for violating constraints
回答by Clodoaldo Neto
CREATE TABLE someTable (
id serial primary key,
col1 int NOT NULL,
col2 int NOT NULL,
unique (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
autoincrement
不是 postgresql。你想要一个serial
.
If col1 and col2 make a unique and can't be null then they make a good primary key:
如果 col1 和 col2 是唯一的并且不能为空,那么它们是一个很好的主键:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
primary key (col1, col2)
)
回答by djangojazz
Create unique constraint that two numbers together CANNOT together be repeated:
创建唯一约束,使两个数字不能一起重复:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)