简体   繁体   English

当列在Postgres中可为空时处理索引冲突

[英]Handling conflicts on Index when columns are nullable in Postgres

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

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');

If I populate this column and have the second field in the index be null, but what to upsert on conflicts where null=null, how can I do this? 如果我填充此列并使索引中的第二个字段为null,但是在null = null的冲突中该如何处理,我该怎么做? Currently I'm not getting a conflict when the upsert value is null as well. 当前,当upsert值也为null时,我不会遇到冲突。

INSERT INTO test (first, second, other)
  VALUES ('lorem', null, 'new')
ON CONFLICT (first, second)
  DO UPDATE SET
    other = EXCLUDED.other;

I will get an output of something like this: 我将得到类似以下内容的输出:

1   lorem   (null)  old
2   lorem   (null)  new

This works if I set the second column to any value, but there's no conflict when they're null. 如果我将第二列设置为任何值,则此方法有效,但是当它们为null时没有冲突。 Why? 为什么? And how can I fix this? 我该如何解决呢?

You can create an index on an expression. 您可以在表达式上创建索引。 What often works is: 通常起作用的是:

CREATE UNIQUE INDEX unique_index ON test (COALESCE(first, ''), COALESCE(second, ''));

Of course, this assumes that '' is not a valid field value. 当然,这假定''不是有效的字段值。 You can always put something else in . 您随时可以放入其他内容。 . . such as '<null>' . '<null>'

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

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