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

时间:2014-07-08 11:32:52

标签: php mysql codeigniter

我有3张桌子: 类别,帖子和评论

类别和帖子通过 categories.id_category = posts.category_id 连接,帖子和评论通过 posts.id_post连接= comments.post_id

当我删除类别时,我还要删除与该类别相关的所有帖子以及与该帖子相关的所有评论。这可以在一个查询中完成吗?

2 个答案:

答案 0 :(得分:3)

MySQL InnoDB数据库支持带有ON DELETE CASCADE子句的FOREIGN KEY约束。使用此规范,在引用的表上执行DELETE时将删除相关的从属表行。

这是一个例子:

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
);

在这里,您可以找到有关在MySQL中使用外键的文档: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

答案 1 :(得分:0)

这里他们给出了格式。这会对你有所帮助。只需遵循这些步骤,它可能有助于您的事业

http://www.java2s.com/Code/SQL/Join/DeleterecordsfromtwotablesusingJOIN.htm

相关问题