删除MySQL中的相关记录

发布于 2024-07-27 15:50:57 字数 314 浏览 6 评论 0原文

我有两个MySQL(MyISAM)表:

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

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

当从“Posts”表中删除相应的帖子记录时,我想删除“Comments”表中属于特定帖子的所有评论。

我知道这可以使用 InnoDB 的级联删除来实现(通过设置外键)。 但是我该如何使用 PHP 在 MyISAM 中做到这一点呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

以酷 2024-08-03 15:50:57
DELETE
    Posts,
    Comments
FROM Posts
INNER JOIN Comments ON
    Posts.PostID = Comments.PostID
WHERE Posts.PostID = $post_id;

假设您的 Comments 表有一个字段 PostID,它指定评论所属的帖子。

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.

下雨或天晴 2024-08-03 15:50:57

即使没有可执行的外键,删除的方法仍然是相同的。 假设您的 Comments 表中有像 post_id 这样的列,

DELETE FROM Comments
 WHERE post_id = [Whatever Id];

DELETE FROM Posts
 WHERE PostID = [Whatever Id];

那么使用 MyISAM 您真正失去的就是在事务中执行这两个查询的能力。

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.

死开点丶别碍眼 2024-08-03 15:50:57

我从未尝试过,但您可以设置一个触发器来执行级联删除(如果您使用的是 >=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 ;

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 ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文