在sqlite中,如何在另一个表/视图列中将列的值限制为不?
例如
sqlite> create table tab1(col1 check (col1 not in (1,2)));
做我想要的,除了它似乎只是排除硬编码值。但是,以下操作无效 -
sqlite> create table tab2(vals_to_exclude);
sqlite> insert into tab2 values(1);
sqlite> insert into tab2 values(2);
sqlite> create table tab3(col1 check (col1 not in (select vals_to_exclude from tab2)));
Error: subqueries prohibited in CHECK constraints
是否可以约束列以排除动态确定的值集?
答案 0 :(得分:0)
如果内置机制不足,请使用trigger:
手动执行检查CREATE TRIGGER tab3_col1_not_in_tab2
BEFORE INSERT ON tab3 -- you also need a trigger for UPDATEs
FOR EACH ROW
WHEN EXISTS (SELECT 1
FROM tab2
WHERE vals_to_exclude = NEW.col1)
BEGIN
SELECT RAISE(FAIL, "col1 conflicts with tab2");
END;
或者,或者:
CREATE TRIGGER tab3_col1_not_in_tab2
BEFORE INSERT ON tab3 -- you also need a trigger for UPDATEs
FOR EACH ROW
BEGIN
SELECT RAISE(FAIL, "col1 conflicts with tab2")
FROM tab2
WHERE vals_to_exclude = NEW.col1;
END;