我在 UPDATE 脚本中完成了类似的 JOIN,但我在 SET 和 WHERE 子句中使用了同一个表。在此 DELETE 脚本中,我需要从一个表中删除另一个表中条件为真的表。例如:
DELETE FROM `db_A`.`table_A`
JOIN `db_B`.`table_B`
ON `table_A`.`id` = `table_B`.`id`
WHERE `table_B`.`name` = 'Remove Me'
我可以做这样的事情吗?
最佳答案
MYSQL documentation非常清楚,是的,你可以做到这一点
You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.
For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted. For the second multiple-table syntax, only matching rows from the tables listed in the FROM clause (before the USING clause) are deleted. The effect is that you can delete rows from many tables at the same time and have additional tables that are used only for searching:
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
Or:
DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
These statements use all three tables when searching for rows to delete, but delete matching rows only from tables t1 and t2.
The preceding examples use INNER JOIN, but multiple-table DELETE statements can use other types of join permitted in SELECT statements, such as LEFT JOIN. For example, to delete rows that exist in t1 that have no match in t2, use a LEFT JOIN:
DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;
The syntax permits .* after each tbl_name for compatibility with Access.
关于mysql - FROM 子句中的表是否必须在 WHERE 子句中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865974/