Null忽略的唯一约束

时间:2018-02-08 17:25:43

标签: sql json postgresql

我正在使用Postgres 9.6,并且在我使用jsonb_populate_recordset时遇到问题。

我在表上创建了UNIQUE约束,但是在执行带有空值的INSERT时,我可以绕过此约束。

是否有办法强制唯一约束只保留1条记录,即使它具有null值,并且之后不允许重复记录?

这是一个简单的例子:

CREATE TABLE person(
    person_id SERIAL PRIMARY KEY,
    person_name TEXT,
    CONSTRAINT unq_person UNIQUE(person_name)
);

INSERT INTO person (person_name) VALUES ('Frank');

CREATE TABLE locations(
  location_id SERIAL PRIMARY KEY,
  city TEXT,
  state TEXT,
  address TEXT,
  address_country TEXT,
  postal_code TEXT,
  person_id INTEGER REFERENCES person(person_id)
  ON DELETE CASCADE,
  CONSTRAINT unq_location UNIQUE(city, state, address, address_country, postal_code, person_id)
);

在此示例中,城市和地址为null(但理论上,它们都可以是null,或记录属性的任意组合。)

每次运行以下查询时,都会插入新记录。我不想要这些记录中的一个以上。

INSERT INTO locations (city, state, address, address_country, postal_code, person_id)
SELECT city, state, address, address_country, postal_code, person_id
FROM jsonb_populate_recordset(NULL::locations, '[{"city": null, "address": null, "address_country": "USA", "state": "NY", "person_id": 1, "postal_code": "10001"}]'::jsonb)

如何在将JSONB对象插入Postgres时只允许1条记录而不是多条记录?

1 个答案:

答案 0 :(得分:0)

到您现有的查询:

insert into locations
(fields)
select values
from etc

添加此过滤器

where not exists 
(select 1
from locations l2
where locations.person_id = l2.person_id
)

它与空值无关。