douza9835 2016-09-21 17:55
浏览 97
已采纳

从table1和表2中关联的记录中删除

I'm trying to make a simple decision deleting records from database. I have a main table with records and the unique ID it's auto increment.

Then I have a second table that stores values(could be more than one) associating the ID from the first table.

Example:

table1
editors
ID (autoincrement)
EditorName

Then I have a second table with:

table2
ID
editorID (same ID as table1)
bookname

So this way I want to know how could be the best way to delete a record from table1 (example ID=2) and it automatically deletes all records from table2 where editorID=2.

I've tried many ways but it seems they don't work unless I do two queries but I don't like that way. There's a smarter way to do that? It must be by code or I could associate two tables in SQL and they associated by ID and editorID?

  • 写回答

3条回答 默认 最新

  • dowb58485 2016-09-22 04:17
    关注

    Solution #1:

    If you have foreign key constraint in table2 which refers to the ID of table1 having ON DELETE CASCADE behavior then deleting records from table1 will delete the corresponding entries from table2.

    Solution #2:

    You can delete multiple tables using JOIN

    DELETE T1,T2
    FROM table1 AS T1
    INNER JOIN table2 AS T2 ON T1.ID = T2.editorID
    WHERE T1.ID = 2;
    

    See <kbd>Related post</kbd>


    EDIT:

    In order to delete entries from table1 and table2 irrespective of whether corresponding entries exist in table2 or not you need to replace the INNER JOIN by LEFT JOIN

      DELETE T1,T2
      FROM table1 AS T1
      LEFT JOIN table2 AS T2 ON T1.ID = T2.editorID
      WHERE T1.ID = 2;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元