让我们假设生命不仅存在于地球上,而且宇宙中还存在其他生物。我有一张桌子,展示了全世界的各种物种
+----+---------------+-------+-------+
| id | name | green | forgn |
+----+---------------+-------+-------|
| 1 | belgian horse | false | false |
| 2 | polar bear | false | false |
| 3 | andromeda dog | true | true |
| 4 | cosmos cat | true | true |
| 5 | amazon parrot | true | false |
...
我们也知道每个外星人(在这种情况下为andromeda dog
和cosmos cat
)都有绿色。所以我想定义一个约束如果forgn
为真,green
也必须为真,但它不适用于其他方式,例如amazon parrot
是一种绿色的动物,它仍然没有生活在地球之外。
我想我应该以某种方式使用CHECK来做,但我不太确定如何。
答案 0 :(得分:1)
如果使用布尔类型,则为true>假的 在这种情况下,您可以使用
CREATE TABLE tablename (
..........
CHECK (green >= forgn)
)
答案 1 :(得分:1)
我在桌子上写了一个略有不同的支票。
test=# \d test_stackoverflow;
Table "public.test_stackoverflow"
Column | Type | Modifiers
--------+---------+-----------
animal | text |
p1 | boolean | not null
p2 | boolean | not null
Check constraints:
"test_stackoverflow_check" CHECK (p2 AND p1 = p2 OR p2 = false)
test=#
insert into public.test_stackoverflow values ('cat', true, true );
INSERT 0 1
test=#
insert into public.test_stackoverflow values ('dog', true, false );
INSERT 0 1
test=#
insert into public.test_stackoverflow values ('parrot', false, true );
ERROR: new row for relation "test_stackoverflow" violates check constraint "test_stackoverflow_check"
DETAIL: Failing row contains (parrot, f, t).
test=#
答案 2 :(得分:0)
您可以在表格上添加插入/更新触发器。
每次更改列的值forgn
时,请更新触发器内的green
列。