我有一个这样定义的表
Table "public.foo"
Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+-------------------------------------
foo_id | integer | | not null | nextval('foo_foo_id_seq'::regclass)
bar_id | integer | | |
approved | boolean | | |
Indexes:
"foo_pkey" PRIMARY KEY, btree (foo_id)
Foreign-key constraints:
"foo_bar_id_fkey" FOREIGN KEY (bar_id) REFERENCES bar(bar_id)
我将如何定义一个排除约束,这样只有一行foo
具有特定的bar_id
才能设置approved
为 true?
例如以下数据:
foo_id | bar_id | approved
--------+--------+----------
1 | 1 | t
2 | 1 |
3 | 2 |
(3 rows)
我将能够将第 3 行设置approved
为 true,因为没有其他行foo_id
3 具有 true 以获得批准。
但是,将第 2 行更新approved
为 true 会失败,因为第 1 行也有foo_id
1 并且已经被批准。