postgres 为空列添加唯一约束返回错误

问题描述 投票:0回答:1

我正在尝试向 postgres 中名为

personnel_id
的空列上的现有表添加唯一约束。大多数记录都为空
personnel_id
。我是这样做的:

ALTER TABLE "myschema"."mytable" ADD UNIQUE NULLS not distinct ("personnel_id");

我收到此错误:

ERROR:  could not create unique index "mytable_personnel_id_key"
DETAIL:  Key (personnel_id)=() is duplicated.

我的 postgres 版本是:

psql (PostgreSQL) 15.3 (Debian 15.3-1.pgdg120+1)
postgresql null unique-constraint
1个回答
0
投票

如果您指定

NULLS NOT DISTINCT
,PostgreSQL 将两个 NULL 值视为不不同,因此您将收到错误。

如果您希望 NULL 不同,也就是说,如果您希望唯一列中存在多个 NULL 值,请使用

NULLS DISTINCT

© www.soinside.com 2019 - 2024. All rights reserved.