说我有一个像这样的表:
CREATE TABLE test (id SERIAL, first VARCHAR(10), second VARCHAR(10), other VARCHAR(10));
CREATE UNIQUE INDEX unique_index ON test (first, second);
INSERT INTO test (first, second, other)
VALUES ('lorem', null, 'old');
如果我填充此列并使索引中的第二个字段为null,但是在null = null的冲突中该如何处理,我该怎么做?当前,当upsert值也为null时,我不会遇到冲突。
INSERT INTO test (first, second, other)
VALUES ('lorem', null, 'new')
ON CONFLICT (first, second)
DO UPDATE SET
other = EXCLUDED.other;
我将得到类似这样的输出:
1 lorem (null) old
2 lorem (null) new
如果我将第二列设置为任何值,则此方法有效,但是当它们为null时没有冲突。为什么?我该如何解决?
答案 0 :(得分:2)
您可以在表达式上创建索引。经常起作用的是:
CREATE UNIQUE INDEX unique_index ON test (COALESCE(first, ''), COALESCE(second, ''));
当然,这假定''
不是有效的字段值。您随时可以放入其他内容。 。 。例如'<null>'
。