是否可以创建一次影响多个列的约束?
假设我正在创建包含位图的表:
CREATE TABLE weekdays
(
id NUMBER(5,0)
monday NUMBER(1,0) NOT NULL DEFAULT 0,
tuesday NUMBER(1,0) NOT NULL DEFAULT 0,
wednesday NUMBER(1,0) NOT NULL DEFAULT 0,
thursday NUMBER(1,0) NOT NULL DEFAULT 0,
Friday NUMBER(1,0) NOT NULL DEFAULT 0,
Saturday NUMBER(1,0) NOT NULL DEFAULT 0,
Sunday NUMBER(1,0) NOT NULL DEFAULT 0,
CONSTRAINT monday_b CHECK (monday IN (1, 0))
--... OTHER WEEKDAYS CONSTRAINSTS HERE
);
由于所有工作日都有相同的约束(值为1或0),是否可以做这样的事情:
CONSTRAINT wd_b CHECK ((monday, tuesday, wednesday, thursday, ...) IN (1, 0))
答案 0 :(得分:3)
您可以执行类似
的操作check(monday in (0,1) and tuesday in (0,1) and...)
然而,如果这是我的表格,我宁愿选择七个单独的约束(也许在列级别定义它们 - 所谓的"内联和#34;约束)。当其中一个值违反时,使用单独的约束我现在将立即确切地违反了哪个约束。对于行级约束,我只会知道"其中一个"被侵犯了。
答案 1 :(得分:0)
您可以构建一个约束来检查所有值是not null
并且它们的值是0或1这样:
CREATE TABLE weekdays
(
id NUMBER(5,0),
monday NUMBER(1,0) DEFAULT 0,
tuesday NUMBER(1,0) DEFAULT 0,
wednesday NUMBER(1,0) DEFAULT 0,
thursday NUMBER(1,0) DEFAULT 0,
Friday NUMBER(1,0) DEFAULT 0,
Saturday NUMBER(1,0) DEFAULT 0,
Sunday NUMBER(1,0) DEFAULT 0,
CONSTRAINT check_all CHECK (regexp_like(monday || tuesday || wednesday || thursday || Friday || Saturday || Sunday, '[01]{7}'))
);
然而,将其视为一种练习:我不推荐这种方法,因为它难以维护,难以阅读,性能不佳,......
答案 2 :(得分:0)
check
(
0 <= all (monday,tuesday,wednesday,thursday,Friday,Saturday,Sunday)
and 1 >= all (monday,tuesday,wednesday,thursday,Friday,Saturday,Sunday)
)
或
check
(
0 <= least (monday,tuesday,wednesday,thursday,Friday,Saturday,Sunday)
and 1 >= greatest (monday,tuesday,wednesday,thursday,Friday,Saturday,Sunday)
)