给定
表格1:
身份证|姓名
表2:
id|table1_id|table3_id
表3:
id|检查(类型=布尔)
现在我想删除table2中的行,当table1的对应行被删除并且对应的table3行被选中=true时。
我必须使用哪个 SQL 语句?
您将需要两个触发器,一个用于检测已选中的设置为 1,一个用于检查从 table1 中的删除。这些有点“又快又脏”,但应该适用于任何最近的 MySQL 版本。
DELIMITER //
CREATE TRIGGER trig_table1 AFTER DELETE ON table1
FOR EACH ROW
BEGIN
DELETE table2.*
FROM table2
JOIN table3
ON table3_id = table3.id
AND table3.checked = 1
AND table1_id = OLD.id;
END;
//
CREATE TRIGGER trig_table3 AFTER UPDATE ON table3
FOR EACH ROW
BEGIN
DELETE table2.*
FROM table2
LEFT JOIN table3
ON table3.id = OLD.id
AND table3.checked = 0
LEFT JOIN table1
ON table1_id = table1.id
AND table3_id = OLD.id
WHERE table2.table3_id = OLD.id
AND table3.id IS NULL
AND table1.id IS NULL;
END;
//
您可以在 MS SQL 上尝试类似的操作。
delete table2 from table2 inner join table3 on table2.table3_id = table3.id
left join table1 on table1.id = table2.table1_id
where table3.checked = true and table1.id is null