Delete with Join in MySQL

后端 未结 14 1303
鱼传尺愫
鱼传尺愫 2020-11-22 06:18

Here is the script to create my tables:

CREATE TABLE clients (
   client_i INT(11),
   PRIMARY KEY (client_id)
);
CREATE TABLE projects (
   project_id INT(         


        
14条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 07:09

    One solution is to use subquery

    DELETE FROM posts WHERE post_id in (SELECT post_id FROM posts p
    INNER JOIN projects prj ON p.project_id = prj.project_id 
    INNER JOIN clients c on prj.client_id = c.client_id WHERE c.client_id = :client_id 
    );
    

    The subquery returns the ID that need to be deleted; all three tables are connected using joins and only those records are deleted that meets the filter condition (in yours case i.e. client_id in the where clause).

提交回复
热议问题