根据另一个 table 中列的值对列使用检查约束
Use check constraint on a column based on the value of a column in another table
我有一个table:
CREATE TABLE teams (
id INTEGER PRIMARY KEY,
member_count INTEGER NOT NULL
);
我还有一个table:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
team_id INTEGER,
member_number INTEGER
FOREIGN KEY (team_id) REFERENCES teams (id)
);
我希望 member_number 的值介于 1 和 member_count(含)之间。我知道我需要在这里使用检查约束,但我不知道如何使用另一个 table 的列来做到这一点。我该怎么做?
检查约束不能引用其他 table,因此您只能通过为 INSERT
和 UPDATE
使用 2 个单独的触发器来实现您想要的:
CREATE TRIGGER insert_member_number BEFORE INSERT ON members
BEGIN
SELECT
CASE
WHEN NEW.member_number NOT BETWEEN 1 AND (SELECT member_count FROM teams WHERE id = NEW.team_id)
THEN RAISE (ABORT, 'Invalid member number')
END;
END;
CREATE TRIGGER update_member_number BEFORE UPDATE ON members
BEGIN
SELECT
CASE
WHEN NEW.member_number NOT BETWEEN 1 AND (SELECT member_count FROM teams WHERE id = NEW.team_id)
THEN RAISE (ABORT, 'Invalid member number')
END;
END;
此外,我认为您应该更改 table 成员的定义,以便 team_id
和 member_number
列的组合为 UNIQUE
:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
team_id INTEGER NOT NULL,
member_number INTEGER NOT NULL,
UNIQUE(team_id, member_number),
FOREIGN KEY (team_id) REFERENCES teams (id)
);
参见demo。
我有一个table:
CREATE TABLE teams (
id INTEGER PRIMARY KEY,
member_count INTEGER NOT NULL
);
我还有一个table:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
team_id INTEGER,
member_number INTEGER
FOREIGN KEY (team_id) REFERENCES teams (id)
);
我希望 member_number 的值介于 1 和 member_count(含)之间。我知道我需要在这里使用检查约束,但我不知道如何使用另一个 table 的列来做到这一点。我该怎么做?
检查约束不能引用其他 table,因此您只能通过为 INSERT
和 UPDATE
使用 2 个单独的触发器来实现您想要的:
CREATE TRIGGER insert_member_number BEFORE INSERT ON members
BEGIN
SELECT
CASE
WHEN NEW.member_number NOT BETWEEN 1 AND (SELECT member_count FROM teams WHERE id = NEW.team_id)
THEN RAISE (ABORT, 'Invalid member number')
END;
END;
CREATE TRIGGER update_member_number BEFORE UPDATE ON members
BEGIN
SELECT
CASE
WHEN NEW.member_number NOT BETWEEN 1 AND (SELECT member_count FROM teams WHERE id = NEW.team_id)
THEN RAISE (ABORT, 'Invalid member number')
END;
END;
此外,我认为您应该更改 table 成员的定义,以便 team_id
和 member_number
列的组合为 UNIQUE
:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
team_id INTEGER NOT NULL,
member_number INTEGER NOT NULL,
UNIQUE(team_id, member_number),
FOREIGN KEY (team_id) REFERENCES teams (id)
);
参见demo。