简体   繁体   English

使用INSERT ON CONFLICT跨多个列碰撞唯一约束,其中之一可能为null

[英]Colliding on unique constraint across multiple columns, one of which may be null, using INSERT ON CONFLICT

Evening all, 整个晚上

Say I have a table, 说我有一张桌子

CREATE TABLE test(
col_1 integer,
col_2 integer,
col_3 integer,
CONSTRAINT test_uk UNIQUE (col_1, col_2, col_3));

Insert two rows; 插入两行;

INSERT INTO test (col_1 ,col_2 ,col_3) VALUES (1,2,NULL),(1,2,NULL);

This doesn't raise an error as postgres treats the nulls as not equal. 这不会引发错误,因为postgres将null视为不相等。 What constraint can I put across these three columns that I can collide on for an update using 我可以对这三列施加什么约束,以便使用更新进行碰撞

INSERT...... ON CONFLICT ... DO UPDATE...;

?

Currently the query will not collide for the above case since, as mentioned, the nulls are not treated as equal. 当前,查询不会针对上述情况发生冲突,因为如上所述,空值不被视为相等。

Thanks in advance. 提前致谢。

Not very classy, but you can coalesce the NULL to some "reserved" value, such as 0 or -1. 不是很经典,但是您可以将NULL合并为某些“保留”值,例如0或-1。 With "reserved" I mean a value that you know it's not going to be part of the potential column values. “保留”是指您知道它不会成为潜在列值的一部分的值。

create unique index idx_1 on test (coalesce(col_1,-1), coalesce(col_2,-1), coalesce(col_3,-1)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM