Deleting related records in MySQL

本小妞迷上赌 提交于 2019-12-23 02:25:08

问题


I have two MySQL (MyISAM) tables:

Posts: PostID(primary key), post_text, post_date, etc. 

Comments: CommentID(primary key), comment_text, comment_date, etc.  

I want to delete all the comments in the "Comments" table belonging to a particular post, when the corresponding post record is deleted from the "Posts" table.

I know this can be achieved using cascaded delete with InnoDB (by setting up foreign keys). But how would I do it in MyISAM using PHP?


回答1:


DELETE
    Posts,
    Comments
FROM Posts
INNER JOIN Comments ON
    Posts.PostID = Comments.PostID
WHERE Posts.PostID = $post_id;

Assuming your Comments table has a field PostID, which designates the Post to which a Comment belongs to.




回答2:


Even without enforceable foreign keys, the method to do the deletion is still the same. Assuming you have a column like post_id in your Comments table

DELETE FROM Comments
 WHERE post_id = [Whatever Id];

DELETE FROM Posts
 WHERE PostID = [Whatever Id];

What you really lose with MyISAM is the ability to execute these two queries within a transaction.




回答3:


I've never tried it, but you could set up a trigger to do cascading deletes (if you are using >=5.0)

DELIMITER $$
CREATE TRIGGER Posts_AD AFTER DELETE ON Posts
FOR EACH ROW
BEGIN
  DELETE FROM Comments WHERE post_id = OLD.PostID;
END $$
DELIMITER ;


来源:https://stackoverflow.com/questions/1126225/deleting-related-records-in-mysql

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