本文介绍了在Postgresql中,对两列组合强制唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在PostgreSQL中建立一个表,使得两列在一起必须唯一。只要没有两个共享这两个值,就可以有多个值。
例如:
创建表someTable( id int主键自动递增, col1 int非空, col2 int非空)因此, col1 和 col2 可以重复,但不能同时重复。因此,将允许这样做(不包括ID)
1 1 1 2 2 1 2 2但不是这样:
1 1 1 2 1 1-会因为违反约束 解决方案CREATE TABLE someTable( id串行主键, col1 int NOT NULL, col2 int NOT NULL,唯一(col1,col2))
自动增量不是postgresql。您想要一个序列。
如果col1和col2唯一且不能为null,则它们将好主键:
创建表someTable( col1 int NOT NULL, col2 int NOT NULL, 主键(col1,col2))
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.
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)
1 1 1 2 2 1 2 2but not this:
1 1 1 2 1 1 -- would reject this insert for violating constraints解决方案 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.
If col1 and col2 make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable ( col1 int NOT NULL, col2 int NOT NULL, primary key (col1, col2) )
更多推荐
在Postgresql中,对两列组合强制唯一
发布评论