sql - 在唯一列中允许空值

标签 sql postgresql database-design null unique-constraint

我创建了下表:

CREATE TABLE MMCompany (
   CompanyUniqueID BIGSERIAL PRIMARY KEY NOT NULL, 
   Name VARCHAR (150) NOT NULL,
   PhoneNumber VARCHAR(20) NOT NULL UNIQUE, 
   Email VARCHAR(75) UNIQUE,
   CompanyLogo BYTEA
 );

email 列是唯一的,它在我的场景中导致了一个“错误”,因为只有一个记录为 null。我试图实现没有相同电子邮件的公司记录,但同时允许公司没有电子邮件。

我怎样才能做到这一点?

最佳答案

这是一个误会。
UNIQUE constraint 正是您想要的。 NULL 值可以在定义为 UNIQUE 的列中的多行中共存。

The manual:

In general, a unique constraint is violated when there is more than one row 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 can be changed by adding the clause NULLS NOT DISTINCT [...]

大胆强调我的。

请注意 character types允许空字符串 (''),它不是 NULL 值并且会像任何其他非空值一样触发唯一违规当输入超过一行时。

Postgres 15 允许子句 NULLS NOT DISTINCT 改变这种行为(与您要求的相反)。我更新了上面的报价。见:

关于sql - 在唯一列中允许空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20154033/

相关文章:

sql - 销售预测的 postgres 查询

mysql - 将数据链接到数据库中的多个实体

.net - 处理一个有很多字段的表

PostgreSQL - 更新失败时返回行内容

python-2.7 - 命令 "python setup.py egg_info"失败,错误代码为 1 pygresql

mysql - 从数据库中获取数据并过滤结果

php - 如何在同一列上使用两个联接

mysql - 嵌套 SQL 查询不起作用

mysql - 使用sql更改mysql中的所有日期但不更改时间

php - 迁移到 Postgresql