我有下表
CREATE TABLE IF NOT EXISTS node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT CHECK(type IN ("DIRECTORY", "EXECUTABLE", "DOCUMENT")) NOT NULL,
siblingOrder INTEGER NOT NULL,
parentId INTEGER,
protected INTEGER NOT NULL,
UNIQUE (parentId, siblingOrder) ON CONFLICT ABORT,
FOREIGN KEY(parentId) REFERENCES node(id),
CONSTRAINT fk_parent
FOREIGN KEY (parentId)
REFERENCES node(id)
ON DELETE CASCADE
);
我插入以下数据
INSERT INTO node (id, name, type, siblingOrder, parentId, protected)
VALUES
(1, "DESKTOP", "DIRECTORY", 0, null, 1),
(2, "sys", "DIRECTORY", 1, 1, 0),
(3, "dont delete me", "DIRECTORY", 2, 2, 1);
我运行以下命令
DELETE FROM node
WHERE id=2;
如何防止删除protected
值为 的记录TRUE
?(在这种情况下,我不希望删除“不要删除我”记录。
Foreign Key 操作是all or nothing,因此无法通过定义外键约束的方式来实现您正在寻找的东西。
相反,您可以将
ON DELETE
操作更改为NO ACTION
永远不会级联删除,并且您可以定义一个DELETE
触发器来检查记录是否存在protected
并在不存在DELETE
时执行。