mysql foreign key “permissions” on delete

那年仲夏 提交于 2019-12-12 03:14:19

问题


I'm working on a little support (ticket) system. My tables are tickets and ticket_replies.

Design of tickets table is

id|user_id|title|...

Design of ticket_replies looks like:

id|ticket_id|...

The foreign key I added looks like this:

 ALTER TABLE `ticket_replies` ADDFOREIGN KEY (`ticket_id`)
 REFERENCES `sampleauth`.`tickets`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; 

Now when I delete a "ticket" in the "ticket" table it gets deleted in "ticket_replies" too. The other way this doesn't work, all in all I would like this to work the other way too, so my database has all the time consistency. How to do so?


回答1:


Add this trigger will delete its primary key when you try to delete foreign key

CREATE TRIGGER `ticket_replies_BEFORE_DELETE` BEFORE DELETE ON `ticket_replies` FOR EACH ROW
BEGIN
    DELETE FROM tickets WHERE id = OLD.ticket_id;
END


来源:https://stackoverflow.com/questions/34871811/mysql-foreign-key-permissions-on-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!