我们有一个如下表:
=# CREATE TABLE items (item_id INT NOT NULL, revision VARCHAR(2) NOT NULL, is_newest_rev BOOLEAN NOT NULL, UNIQUE (item_id,revision));
=# SELECT * FROM items;
item_id | revision | is_newest_rev
---------+----------+---------------
250 | 1A | f
250 | 1B | t
199 | 1F | t
40 | 1A | f <-note this, false
40 | 1B | f <-note this, false
40 | 1C | t <-note this, true
上表有效。
下表无效:
=# SELECT * FROM items;
item_id | revision | is_newest_rev
---------+----------+---------------
250 | 1A | f
250 | 1B | t
199 | 1F | t
40 | 1A | f <-note this, false
40 | 1B | f <-note this, false
40 | 1C | t <-note this, true
40 | 1D | t <-ERROR! 40 | 1C is already marked as true!
我需要创建一个约束来检查插入查询,然后再将其应用于表;检查每个 item_id
和 revision
是否只有一个 t
实例。
所以,如果我尝试运行 INSERT INTO items VALUES (40, '1D', 't');
它会失败,因为 40, 1C
是已标记为 t
。如果 40
的所有修订版都标记为 f
,那么它将起作用。希望这是有道理的。
抱歉标题措辞不当,我发现很难命名问题。
最佳答案
这可以用 partial unique index 来解决.
考虑:
CREATE UNIQUE INDEX items_custom
ON items (item_id, is_newest_rev)
WHERE (is_newest_rev = 't');
CREATE TABLE items (
item_id INT NOT NULL,
revision VARCHAR(2) NOT NULL,
is_newest_rev BOOLEAN NOT NULL,
UNIQUE (item_id,revision)
);
CREATE UNIQUE INDEX items_custom
ON items (item_id, is_newest_rev)
WHERE (is_newest_rev = 't');
insert into items values(40, '1A', 't');
insert into items values(40, '1B', 'f');
insert into items values(40, '1C', 't');
ERROR: duplicate key value violates unique constraint "items_custom"
DETAIL: Key (item_id, is_newest_rev)=(40, t) already exists.
关于sql - 检查一个值在每一列的一列中只能存在一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421384/