![](/img/trans.png)
[英]Is there a way to validate, from the DBMS side, if a “boolean” column is already checked (true) in the table but for a subset of rows only
[英]How do I put a constraint on a table to ensure only one boolean column across a subset of tables is true?
我想知道如何将特定的布尔列限制为仅对表中的某个行子集为true。
在下面的示例中,对于元组(id2, 1d3)
具有相同值的行应该只在默认列中有一个true:
$> SELECT * FROM records WHERE id2 = 2 AND id3 = 3;
$> id | id2 | id3 | name | default
------+-------+-------+--------+---------
1 | 2 | 3 | bob | false
2 | 2 | 3 | jane | false
3 | 2 | 3 | jim | false
4 | 2 | 3 | cory | true
5 | 2 | 3 | alan | false
$> SELECT * FROM records WHERE id2 = 4 AND id3 = 5;
$> id | id2 | id3 | name | default
------+-------+-------+--------+---------
6 | 4 | 5 | bill | false
7 | 4 | 5 | fred | false
8 | 4 | 5 | frank | false
9 | 4 | 5 | dave | true
10 | 4 | 5 | ryan | false
您可以使用部分唯一索引来执行此操作:
create unique index on records (id2, id3) where "default";
请注意, default
是保留字,因此对于列名称来说是一个非常糟糕的选择。
有一个单独的表,其中一行包含所需行的mainOfferName。 然后查询为:
select yt.*, (nt.id is not null) as valueFlag from records yt left join
newtable nt
on yt.id = nt.id;
如果要更改值,请更改newtable中的值。
注意:您可以将查询放入视图中,只读用户也可以使用。
而且,您可以使用records
上的update
触发器来实现此功能。 它不会更新records
,而是更新newtable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.