我在 postgres 上有这样的行:
name | address | college
john | rome |
john | rome |
max | tokyo |
我创建了一个这样的表:
create test (
name varchar(10),
address varchar(20),
college varchar(20),
constraint test_uq unique (name,address,college);
我怎样才能让空值变得唯一,所以输出可以是这样的:
name | address | college
john | rome |
max | tokyo |
最佳答案
Postgres 文档 claims此行为符合 SQL 标准:
In general, a unique constraint is violated when there are two or more rows in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard[.]
一种可能性是重新考虑您的架构(老实说,name+address+college
的唯一性约束在您的示例中没有多大意义)。
关于database - 空值不是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7752833/