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(
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).
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".
delete table1 from table1 t1
where t1.code = ''
and 0=(select count(t2.name) from table2 t2 where t2.name=t1.name);
Try like below:
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
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:
DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition
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.
-- Note that you can not use an alias over the table where you need delete
DELETE tbl_pagos_activos_usuario
FROM tbl_pagos_activos_usuario, tbl_usuarios b, tbl_facturas c
Where tbl_pagos_activos_usuario.usuario=b.cedula
and tbl_pagos_activos_usuario.cod=c.cod
and tbl_pagos_activos_usuario.rif=c.identificador
and tbl_pagos_activos_usuario.usuario=c.pay_for
and tbl_pagos_activos_usuario.nconfppto=c.nconfppto
and NOT ISNULL(tbl_pagos_activos_usuario.nconfppto)
and c.estatus=50
Another method of deleting using a sub select that is better than using IN
would be WHERE
EXISTS
DELETE FROM posts
WHERE EXISTS ( SELECT 1
FROM projects
WHERE projects.client_id = posts.client_id);
One reason to use this instead of the join is that a DELETE
with JOIN
forbids the use of LIMIT
. If you wish to delete in blocks so as not to produce full table locks, you can add LIMIT
use this DELETE WHERE EXISTS
method.