UNIQUE约束但仅限于column = something

时间:2013-08-27 11:41:23

标签: sql sqlite pdo constraints unique

这在SQLite中是否可行?

像:

UNIQUE(col1, col2 = "something", col3),

我的意思是独特的:

#1  col1=Foo | col2=Foo       | col3=Foo   > OK
#2  col1=Foo | col2=Foo       | col3=Foo   > OK
#3  col1=Foo | col2=something | col3=Foo   > OK
#4  col1=Foo | col2=something | col3=Foo   > Should fail because of #3
#5  col1=Foo | col2=something | col3=Bar   > OK
#6  col1=Foo | col2=something | col3=Bar   > Should fail because of #5

3 个答案:

答案 0 :(得分:3)

不直接支持此功能;你必须用触发器实现它:

CREATE TRIGGER something_unique_check
BEFORE INSERT ON MyTable
FOR EACH ROW
WHEN NEW.col2 = 'something'
BEGIN
    SELECT RAISE(FAIL, '"something" record is not unique')
    FROM MyTable
    WHERE col1 = NEW.col1
      AND col2 = NEW.col2
      AND col3 = NEW.col3;
END;

答案 1 :(得分:2)

我没有测试过,但我认为你可以用partial indexes in SQLite 3.8.0(2013-08-26发布)来做到这一点:

CREATE UNIQUE INDEX
    "partial_index" ON "table" ("col1", "col2", "col3")
WHERE ("col2" = 'something');

我可能错了。

答案 2 :(得分:1)

我建议使用表级cheque约束

ALTER TABLE T
ADD CONSTRAINT CK_something CHECK (col2 != "something" OR (col1<>col2 AND col1<>col3 AND col2<>col3))

其他选择是使用触发器,但这是一种更复杂的方法。