[英]Is it possible to use IS NOT DISTINCT FROM in an exclusion constraint?
I have the following table: 我有下表:
CREATE TABLE claim (
claim_number TEXT NOT NULL,
line_id TEXT,
process TEXT NOT NULL
);
I want to add a constraint to it so that the combination of claim_number and line_id is always unique. 我想为其添加一个约束,以便Claim_number和line_id的组合始终是唯一的。
In most cases line_id is null and there will only be a single row for that claim number. 在大多数情况下,line_id为null,并且该声明编号只有一行。 In some cases there will be multiple rows for a given claim_number and in those cases line_id will always contain a value.
在某些情况下,给定的claim_number将有多行,在这些情况下,line_id将始终包含一个值。 The goal here is to be able to have a constraint that forces a unique combination on the (claim_number, line_id) combo so that I can use it as a conflict target in an
INSERT...ON CONFLICT DO UPDATE
statement so that the process column can be updated. 这里的目标是能够有一个约束,使(claim_number,line_id)组合上具有唯一组合,以便我可以将其用作
INSERT...ON CONFLICT DO UPDATE
语句中的冲突目标,以便处理列可以更新。 A UNIQUE constraint won't work because it doesn't evaluate NULL = NULL, which makes sense, but isn't what I need. UNIQUE约束不起作用,因为它不评估NULL = NULL,这很有意义,但这不是我所需要的。
I have tried adding an exclusion constraint such as: 我尝试添加排除约束,例如:
ALTER TABLE claim
ADD EXCLUDE ( claim_number WITH =,
line_id WITH IS NOT DISTINCT FROM);
But that fails with: 但这失败了:
ERROR: syntax error at or near "IS"
Is there a way to use IS NOT DISTINCT FROM
in an exclusion constraint? 有没有办法在排除约束中使用
IS NOT DISTINCT FROM
?
In MSSQL Server, this is done using a Filtered Unique Index, where the filter predicate is that it only indexes rows with non- NULL
values. 在MSSQL Server中,这是使用“已过滤的唯一索引”完成的,其中过滤条件是它仅索引具有非
NULL
值的行。
I'm not a PostgreSQL expert, but Googling shows it's possible using a "Partial Index": https://www.postgresql.org/docs/current/static/indexes-partial.html 我不是PostgreSQL专家,但是Google搜索显示使用“部分索引”是可行的: https : //www.postgresql.org/docs/current/static/indexes-partial.html
CREATE UNIQUE INDEX ix_claim_lines ON claim ( claim_number, line_id )
WHERE line_id IS NOT NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.