2017-08-30 1 views
1

Considérons une table contenant des colonnes null-able abc, def et xyz. Comment puis-je appliquer:Comment appliquer plusieurs ensembles uniques (combinaisons de colonnes) pour s'exclure mutuellement dans SQLite?

  1. Set 1 ('abc') être unique si 'abc' est pas nul, et
  2. Set 2 ('def, xyz') être UNIQUE si les deux 'def' et 'xyz' ne sont pas null, et
  3. Un seul des ensembles ci-dessus est valide (contient des non-null).

Voici le code que j'ai essayé:

--# 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 
-- 

Mais, tous les 14 inserts sont RÉUSSIR, quand je voulais seulement la première 2 réussissiez.

Répondre

1

En d'autres termes: la ity NULL des colonnes abc et def doit être différent, alors que celle des def et xyz colonnes devraient être les mêmes.

Cela peut être fait avec deux contraintes de table supplémentaires:

CHECK((abc IS NULL) <> (def IS NULL)), 
CHECK((def IS NULL) = (xyz IS NULL)) 
+0

Merci CL. Je voulais vérifier si vous pouviez m'aider avec une autre question que j'ai posté liée à ceci (une extension de ceci): https://stackoverflow.com/questions/45979764/ –