简体   繁体   English

PHP,MySQL-使用联接从多个表中删除

[英]PHP, MySQL - delete from multiple tables with join

I have 3 tables: categories, posts and comments . 我有3个表格: 类别,帖子和评论

categories and posts are connected via categories.id_category = posts.category_id and posts and comments are connected via posts.id_post = comments.post_id . 类别和帖子通过category.id_category = posts.category_id连接, 帖子和评论通过posts.id_post = comments.post_id连接。

When I delete category , I want also to delete all the posts related to that category and all comments related to that posts. 当我删除类别时 ,我还要删除与该类别相关的所有帖子以及与该帖子相关的所有评论。 Can this be done in one query? 可以在一个查询中完成吗?

MySQL InnoDB databases support the FOREIGN KEY constraint with ON DELETE CASCADE clause. MySQL InnoDB数据库通过ON DELETE CASCADE子句支持FOREIGN KEY约束。 With this specifications, related dependent table rows will be deleted when doing a DELETE on the referred table. 使用此规范,对引用的表执行DELETE时,相关的从属表行将被删除。

This is an example: 这是一个例子:

CREATE TABLE categories (
    id_category int unsigned not null primary key,
    ...
);
CREATE TABLE posts (
    id_post int unsigned not null primary key,
    category_id int unsigned not null,
    ...
    FOREIGN KEY (category_id) REFERENCES categories (id_category)
       ON DELETE CASCADE
);
CREATE TABLE comments (
    post_id int unsigned not null,
    ...
    FOREIGN KEY (post_id) REFERENCES posts (id_post)
       ON DELETE CASCADE
);

Here you can find documentation about the use of foreign keys in MySQL: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html 在这里,您可以找到有关在MySQL中使用外键的文档: http : //dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

here they have given the format. 在这里,他们给出了格式。 this will help you. 这将为您提供帮助。 just follow the steps and it might help your cause 只需按照以下步骤操作,这可能对您的事业有所帮助

http://www.java2s.com/Code/SQL/Join/DeleterecordsfromtwotablesusingJOIN.htm http://www.java2s.com/Code/SQL/Join/使用JOIN.htm从twotables删除记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM