条件约束唯一

时间:2012-04-19 15:20:35

标签: sqlite constraints unique

我有下一张桌子

create table use_flags3 (
    id INTEGER,
    flag_name VARCHAR NOT NULL,        
    flag_description VARCHAR NOT NULL,
    flag_type_id INTEGER NOT NULL,
    package_id INTEGER,
    FOREIGN KEY (flag_type_id) REFERENCES use_flags_types(id),
    FOREIGN KEY (package_id) REFERENCES packages(id),
    PRIMARY KEY (id)
);

当flag_type_id等于1时,我需要flag_name列为唯一 。我尝试使用下一个约束来实现此目的

CONSTRAINT idx1_chk CHECK (
    flag_type_id in (select id from use_flags_types where flag_type="local") or
    flag_type_id in (select id from use_flags_types where flag_type="expand") or
    flag_type_id in (select id from use_flags_types where flag_type="expand_hidden") or
    (
         flag_type_id in (select id from use_flags_types where flag_type="global") and
         flag_name not in (select flag_name from use_flags)
    )
)

sqlite说'CHECK约束中禁止'子查询'。我可以替换

flag_type_id in (select id from use_flags_types where flag_type="local")

flag_type_id = ${ID_HERE} -- id from `select id from use_flags_types where flag_type="local"`

但我不能对约束的最后一部分的第二个子部分做同样的技巧

flag_name not in (select flag_name from use_flags)

有没有机会在一张桌子里做我原本想要的东西(我真的不喜欢将这些数据分成2(+)个表格)?

//希望描述很清楚

1 个答案:

答案 0 :(得分:3)

如果您有复杂的约束,则应使用触发器:

http://sqlfiddle.com/#!7/2094c

CREATE TABLE use_flags3 (
    id INTEGER,
    flag_name VARCHAR NOT NULL,
    flag_description VARCHAR NOT NULL,
    flag_type_id INTEGER NOT NULL,
    package_id INTEGER,
    FOREIGN KEY (flag_type_id) REFERENCES use_flags_types(id),
    FOREIGN KEY (package_id) REFERENCES packages(id),
    PRIMARY KEY (id)
);

/* TRIGGER BEFORE UPDATE version omitted */

CREATE TRIGGER fake_unique
BEFORE INSERT ON use_flags3
FOR EACH ROW
WHEN (
    EXISTS (SELECT NULL
            FROM use_flags_types
            WHERE flag_type IN( "local", "expand", "expand_hidden")
              AND flag_type_id = id
           )
    OR (
         EXISTS (SELECT NULL
                 FROM use_flags_types
                 WHERE flag_type="global"
                 AND flag_type_id = id)
         AND flag_name NOT IN (SELECT flag_name FROM use_flags)
    )
)
BEGIN
  SELECT RAISE( ABORT, 'duplicate rows' );
END;