3

我有下一张桌子

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 说“检查约束中禁止的子查询”。我可以换

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(+) 表)?

// 希望描述清楚

4

1 回答 1

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;
于 2012-06-23T18:59:24.427 回答