table1:
ID |名称
table2:
ID | table1_id | table3_id
表3:
ID |检查(类型= BOOLEAN)
现在我想在删除table1的相应行并删除相应的 table3 行时删除table2中的行。
我必须使用哪种SQL语句?
答案 0 :(得分:1)
您需要两个触发器,一个用于检测已设置为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;
//
答案 1 :(得分:0)
你可以在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