duanlu1279 2014-07-08 11:32
浏览 19
已采纳

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

I have 3 tables: categories, posts and comments.

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.

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?

  • 写回答

2条回答 默认 最新

  • doukangbin9698 2014-07-08 11:43
    关注

    MySQL InnoDB databases support the FOREIGN KEY constraint with ON DELETE CASCADE clause. With this specifications, related dependent table rows will be deleted when doing a DELETE on the referred table.

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办