假设一个名为Mytable的表有两列C1和C2。 我希望将这两列列为互斥。
我的意思是,如果我在此表中该行的一列C1中输入值,则db不应允许在C2中输入,反之亦然。
在任何情况下,应该允许其中一列具有数据,而不是两者(两者中的NULL值除外)。
是否可以通过为此表创建触发器?
答案 0 :(得分:1)
ALTER TABLE mytable
ADD CONSTRAINT constraint_name CHECK (c1 is null or c2 is null)
答案 1 :(得分:1)
我的意思是,如果我在此表的该行的一列C1中输入值,则db不应允许在C2中输入,反之亦然。 在任何情况下,应允许其中一列具有数据,而不是两者(两者中的NULL值除外)。
这样的事可能吗?
ALTER TABLE mytable
ADD CONSTRAINT constraint_name CHECK ((c1 is null and c2 is null) or
(c1 is not null and c2 is null) or
(c1 is null and c2 is not null))
使用Karnaugh map或简单逻辑,您可以将其重写为:
ALTER TABLE mytable
ADD CONSTRAINT constraint_name CHECK (not (c1 is not null and c2 is not null))
事实证明,唯一无效的组合是"具有c1和c2" 的值。