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(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
In my PHP code, when deleting a client, I want to delete all projects posts:
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
The posts table does not have a foreign key client_id
, only project_id
. I want to delete the posts in projects that have the passed client_id
.
This is not working right now because no posts are deleted.
You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!
I'm more used to the subquery solution to this, but I have not tried it in MySQL:
MySQL DELETE records with JOIN
You generally use INNER JOIN in the SELECT statement to select records from a table that have corresponding records in other tables. We can also use the INNER JOIN clause with the DELETE statement to delete records from a table and also the corresponding records in other tables e.g., to delete records from both T1 and T2 tables that meet a particular condition, you use the following statement:
Notice that you put table names T1 and T2 between DELETE and FROM. If you omit the T1 table, the DELETE statement only deletes records in the T2 table, and if you omit the T2 table, only records in the T1 table are deleted.
The join condition T1.key = T2.key specifies the corresponding records in the T2 table that need be deleted.
The condition in the WHERE clause specifies which records in the T1 and T2 that need to be deleted.
You just need to specify that you want to delete the entries from the
posts
table:EDIT: For more information you can see this alternative answer
Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:
In this case,
table_name1
andtable_name2
are the same table, so this will work:You can even delete from both tables if you wanted to:
Note that
order by
andlimit
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:
Contributions from Carpetsmoker and etc.
-- Note that you can not use an alias over the table where you need delete