sql - 检查一个值在每一列的一列中只能存在一次

标签 sql postgresql boolean constraints

我们有一个如下表:

=# 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_idrevision 是否只有一个 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');

Demo on DB Fiddle :

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/

相关文章:

sql - 如何根据程序订单更新日期列?

sql - 克隆同一个表中的记录

postgresql - 如何查找建表时间?

c++ - 为什么总是得到相同的 boolean 值?

c++ - 使用动态 boolean 数组的问题

php - 登录 session 问题

javascript - 将输入类型=日期值传递给日期函数以获得特定格式

sql - 如何在 DO block 中执行选择查询?

sql - DROP FUNCTION 不知道参数的数量/类型?

objective-c - NSArray 和 bool 值