gpt4 book ai didi

php - 仅当所有行都不存在时删除关系行

转载 作者:行者123 更新时间:2023-11-29 12:54:19 25 4
gpt4 key购买 nike

我正在使用外键尝试检查用户删除表 gallery gallery_id 0 时是否存在行 gallery_id = 0 存在则删除表article_gallery

我知道可以使用 php 检查是否不存在行然后删除,但想知道是否还有其他方法可以做得更聪明吗?
我尝试了外键,但它应该不起作用,如果删除表gallery中的任何gallery_id = 0,它会删除表article_gallery中的行,即使它还有另一行gallery_id = 0

CONSTRAINT `article_gallery_ibfk_2` FOREIGN KEY (`gallery_id`) REFERENCES `gallery` (`gallery_id`) ON DELETE CASCADE

表:article_gallery

id | article_id | gallery_id  
---------------------------------------------------------
0 0 0
1 1 0
2 2 1

表格:图库

id | gallery_id  
---------------------------------------------------------------------
0 0
1 0
2 0
3 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 ;

关于php - 仅当所有行都不存在时删除关系行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24300149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com