我创建了下表:
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
的列中的多行中共存。
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/