代码之家  ›  专栏  ›  技术社区  ›  Rob

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

  •  0
  • Rob  · 技术社区  · 6 年前

    假设我有一张这样的桌子:

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

    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
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   Gordon Linoff    6 年前

    可以在表达式上创建索引。通常有效的方法是:

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

    当然,这是假设 '' '<null>' .