Delete with Join in MySQL

后端 未结 14 1018
鱼传尺愫
鱼传尺愫 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 06:55

    Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:

    DELETE posts FROM posts
    INNER JOIN projects ON projects.project_id = posts.project_id
    WHERE projects.client_id = :client_id
    

    In this case, table_name1 and table_name2 are the same table, so this will work:

    DELETE projects FROM posts INNER JOIN [...]
    

    You can even delete from both tables if you wanted to:

    DELETE posts, projects FROM posts INNER JOIN [...]
    

    Note that order by and limit don't work for multi-table deletes.

    Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:

    DELETE p FROM posts as p INNER JOIN [...]
    

    Contributions from Carpetsmoker and etc.

提交回复
热议问题