我的问题是关于检查约束,正常的语法是:
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK( status IN('Destroyed', 'constructed'))
这意味着应该销毁或构建列状态。
在下文中,我指定营房不接受空值
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK(status IN('Destroyed', 'constructed')
AND status IS NOT NULL)
现在我添加了列colour
。我想指定如果 barracks
构造,那么colour
应仅 RED 且列状态应为 NOT NULL
如果BARRACKS DESTROYED
然后colour
应为 BLACK , STATUS 列应为 NULL 。
所以这是我写的检查约束:
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK( ((status IN ('Destroyed', 'constructed')
AND status IS NOT NULL)
AND (color IN('RED') ))
OR (( status IN('Destroyed', 'constructed')
AND status IS NULL)
AND (color IN('BLACK') )))
如果颜色为红色,我仍然可以将NULL
插入到列status
中。如何解决这个约束,它将检查我上面提到的条件?
答案 0 :(得分:3)
使用CHECK约束强制执行'Destroyed','construct'等值是个坏主意。改为使用外键来查找表。除了其他任何东西,这将防止逻辑荒谬,如:
( status IN('Destroyed', 'constructed')
AND status IS NULL)
然后您还有一个更简单的检查条件:
( ( status is not null and color = 'RED')
or ( status is null and color = 'BLACK')
至少你应该有两个单独的检查约束:一个用于验证STATUS的值,另一个用于验证COLOR与是否填充STATUS之间的关系。
更多关于外键的信息。创建一个这样的表:
create table barracks_statuses
( status varchar2 (15) not null
, constraint bsts_pk primary key (status)
organization index;
insert into barracks_statuses values ( 'Destroyed');
insert into barracks_statuses values ( 'constructed');
然后强制执行这样的外键:
alter table barracks
add constraint barr_bsts_fk foreign key (status)
references (status);
这种方法很有用,因为它提供了更大的灵活性。您添加了一个新的状态,例如“已计划”或使用DML修复“构造”中的拼写错误,或者重写一些错综复杂的检查约束。