4

这在 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
4

3 回答 3

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;
于 2013-08-27T12:41:01.293 回答
2

我尚未对其进行测试,但我认为您可以使用SQLite 3.8.0 (2013-08-26 发布)中的部分索引来做到这一点:

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

不过我可能是错的。

于 2013-09-02T00:53:02.773 回答
1

我建议使用表级cheque约束

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

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

于 2013-08-27T11:50:01.597 回答