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.
DELETE records FROM one table :
DELETE RECORDS FROM both tables:
If join does not work for you you may try this solution. It is for deleting orphan records from t1 when not using foreign keys + specific where condition. I.e. it deletes records from table1, that have empty field "code" and that do not have records in table2, matching by field "name".
Single Table Delete:
In order to delete entries from
posts
table:In order to delete entries from
projects
table:In order to delete entries from
clients
table:Multiple Tables Delete:
In order to delete entries from multiple tables out of the joined results you need to specify the table names after
DELETE
as comma separated list:Suppose you want to delete entries from all the three tables (
posts
,projects
,clients
) for a particular client :Another method of deleting using a sub select that is better than using
IN
would beWHERE
EXISTS
One reason to use this instead of the join is that a
DELETE
withJOIN
forbids the use ofLIMIT
. If you wish to delete in blocks so as not to produce full table locks, you can addLIMIT
use thisDELETE WHERE EXISTS
method.Try like below:
Try this,