我正在使用外键试图检查当用户删除表gallery
gallery_id
0
时,是否存在行gallery_id = 0
然后删除表{{1} }。
我知道它可以使用php检查如果没有行然后删除,但想知道是否有任何其他方法可以
做得更聪明?
我尝试了外键,但它应该不起作用,如果删除表article_gallery
中的任何article_gallery
,它会删除表gallery_id = 0
中的行,即使它仍然有另一行gallery
。< / p>
gallery_id = 0
表:article_gallery
CONSTRAINT `article_gallery_ibfk_2` FOREIGN KEY (`gallery_id`) REFERENCES `gallery` (`gallery_id`) ON DELETE CASCADE
表:图库
id | article_id | gallery_id
---------------------------------------------------------
0 0 0
1 1 0
2 2 1
答案 0 :(得分:1)
使用触发器:
DELIMITER //
CREATE TRIGGER delete_gallery AFTER DELETE ON gallery
FOR EACH ROW BEGIN
DELETE FROM article_gallery AS a
WHERE a.gallery_id = OLD.gallery_id
AND NOT EXISTS (SELECT *
FROM gallery AS g
WHERE g.gallery_id = OLD.gallery_id);
END
//
DELIMITER ;