database - 空值不是唯一的

标签 database postgresql null

我在 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/

相关文章:

mysql - 将古吉拉特语文本插入 MySQL 表会导致出现垃圾字符和不可读的文本

postgresql - 如何在 Postgresql 中使用内联 View (从子句中选择)进行外部连接

postgresql - PL/pgSQL 函数中的动态 SELECT INTO

SQL-Server 用 NULL 值替换空单元格

java - 嵌入式数据库和加密

mysql优化: is there any way to make this faster?

database - MVD 公理和属性

postgresql - 将表从一个数据库移动到另一个数据库 - 仅插入缺失的行

c - 当没有更多空间时,编译器如何添加空终止符?

vb.net - 使用LINQ过滤DBNull