[英]How do I put a constraint on a table to ensure only one boolean column across a subset of tables is true?
I'm wondering how I can constrain a particular boolean column to only be true for a certain subset of rows in a table. 我想知道如何将特定的布尔列限制为仅对表中的某个行子集为true。
in the example below rows with the same values for tuples (id2, 1d3)
should only have one true in the default column: 在下面的示例中,对于元组
(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
You can do that with a partial unique index: 您可以使用部分唯一索引来执行此操作:
create unique index on records (id2, id3) where "default";
Note that default
is a reserved word and thus a very bad choice for a column name. 请注意,
default
是保留字,因此对于列名称来说是一个非常糟糕的选择。
Have a separate table with one row that contains the mainOfferName of the row that you want. 有一个单独的表,其中一行包含所需行的mainOfferName。 Then query as:
然后查询为:
select yt.*, (nt.id is not null) as valueFlag from records yt left join
newtable nt
on yt.id = nt.id;
When you want to change the value, change the value in newtable. 如果要更改值,请更改newtable中的值。
Note: you can put the query into a view and read-only users will just work. 注意:您可以将查询放入视图中,只读用户也可以使用。
And, you could implement this with an update
trigger on records
. 而且,您可以使用
records
上的update
触发器来实现此功能。 Instead of updating records
, it would update newtable. 它不会更新
records
,而是更新newtable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.