只有当所有行都不存在时才删除关系行

时间:2014-06-19 06:32:44

标签: php mysql foreign-keys

我正在使用外键试图检查当用户删除表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  

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 ;