1
考慮含ABC爲空的列,DEF和XYZ表。如何強制應用經過:如何執行多個獨特集(列組合)是相互排斥的SQLite中?
- 組1(「ABC」)是獨一無二的,如果「ABC」不爲空,並
- 集2(「閃避,XYZ」)是獨一無二的,如果既有「變形點焊」和「XYZ」不爲空,並且
- 上述集只有一個是有效的(包含非空值)。
這是我曾嘗試代碼:
--# sqlite3 --version
-- 3.13.0 ....
DROP TABLE IF EXISTS try;
CREATE TABLE try(
-- 'abc' should be null, when 'def' and 'xyz' are not null.
-- 'abc' should be not be null, when 'def' and 'xyz' are null.
-- 'def' and 'xyz' should be null, when 'abc' is not null.
-- 'def' and 'xyz' should be not be null, when 'abc' is null.
abc TEXT,
def TEXT,
xyz TEXT,
CONSTRAINT combo_1 UNIQUE(abc),
CONSTRAINT combo_2 UNIQUE(def, xyz)
);
INSERT into try(abc) VALUES("a1"); -- should succeed
INSERT into try(def, xyz) VALUES("d2", "x2"); -- should succeed
--
INSERT into try(abc) VALUES(null); -- should not be allowed
INSERT into try(abc, def) VALUES("a4", "d4"); -- should not be allowed
INSERT into try(abc, xyz) VALUES("a5", "x5"); -- should not be allowed
INSERT into try(abc, def, xyz) VALUES("a6", "d6", "x6"); -- should not be allowed
--
INSERT into try(def) VALUES(null); -- should not be allowed
INSERT into try(def) VALUES("d8"); -- should not be allowed
--
INSERT into try(xyz) VALUES(null); -- should not be allowed
INSERT into try(xyz) VALUES("x10"); -- should not be allowed
--
INSERT into try(def, xyz) VALUES(null, null); -- should not be allowed
INSERT into try(def, xyz) VALUES("d12", null); -- should not be allowed
INSERT into try(def, xyz) VALUES(null, "x13"); -- should not be allowed
INSERT into try(abc, def, xyz) VALUES(null, null, null); -- should not be allowed
.headers ON
select rowid,* from try;
.echo on
--
-- Only these 2 rows should be present:
-- 1|a1||
-- 2||d2|x2
--
但是,所有的14個刀片成功,當我想只有第2成功。
感謝CL:
這可以有兩個額外的表約束來實現。我想檢查,如果你能幫助我和其他問題,我發佈與此相關的(這個部分的延長):https://stackoverflow.com/questions/45979764/ –