在一个语句中从多个表中删除

Delete from multiple tables in one statement

使用 MySQL 我正在尝试一次从多个表中删除多条记录。 最初我想做这样的事情:

DELETE t1, t2
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.table1_id
JOIN table3 t3 ON t1.id = t3.table1_id
WHERE t1.id IN (?,?,?,?);

但是,如果表 2 中没有现有记录,我是否会将 JOIN 更改为 LEFT JOIN?此外,如果我只删除八个表 (2x2x2x2x2x2x2x2) 中的两个或三个记录,这样做会导致延迟吗?

是的,将 table2 上的连接更改为 left join 即可。 table1 中属于列表和 table3 的行都将被删除,无论它们是否也存在于 table2 中。同时,table2 中可能匹配的行也将被删除。

delete t1, t2
from table1 t1
left join table2 t2 on t1.id = t2.table1_id
inner join table3 t3 on t1.id = t3.table1_id
where t1.id in (?, ?, ?, ?);

我建议将 table3 上的 join 重写为 exists 条件。这使得查询的意图更加明显,并且可能执行得更好,特别是如果您在 table3(table1_id):

上有索引
delete t1, t2
from table1 t1
left join table2 t2 on t1.id = t2.table1_id
where 
    t1.id in (?, ?, ?, ?)
    and exists (select 1 from table3 t3 where t3.table1_id = t1.id)