[英]How to enforce that there is only one `true` value in a column per names (in an enum) of another column?
I have the following structure with an enum { 'ready', 'set', 'go'}
on name
:我有一个枚举结构如下
{ 'ready', 'set', 'go'}
的name
:
|----------------------|---------------------------|------------------------|
| Id | enabled | name |
|----------------------|---------------------------|------------------------|
| 1 | true | 'ready' |
|----------------------|---------------------------|------------------------|
| 2 | false | 'ready' |
|----------------------|---------------------------|------------------------|
| 3 | false | 'ready' |
|----------------------|---------------------------|------------------------|
| 4 | false | 'set' |
|----------------------|---------------------------|------------------------|
| 5 | true | 'set' |
|----------------------|---------------------------|------------------------|
| 6 | true | 'go' |
|----------------------|---------------------------|------------------------|
| 7 | false | 'go' |
|----------------------|---------------------------|------------------------|
How can I put a constraint on it so that there will only ever be 3 true
's (one on ready
, one on set
, and one on go
)?我如何对其施加约束,以便只有 3 个
true
(一个在ready
,一个 on set
,一个 on go
)?
You can use filtered unique indexes (or as Postgres calls them "partial indexes" ):您可以使用过滤的唯一索引(或者 Postgres 称它们为“部分索引” ):
create unique index unq_t_name
on t(name)
where enabled;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.