mysql - FROM 子句中的表是否必须在 WHERE 子句中?

标签 mysql sql join sql-delete

我在 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/

相关文章:

php - 用户 'root' @'localhost' 的访问被拒绝(使用密码 : YES) using MAMP server

.net - EntityFramework 包括 vs 连接性能

php - 如何使用 PHP 将 MySQL 查询结果作为嵌套数组获取?

mysql 选择重复值的位置

mysql - Zabbix 看一个 MySQL 表

sql - 在 select 中添加 "-"而不是空格

sql - 查找 Postgres 数组中所有位置的所有元素的出现次数(计数)?

php - Login.php 代码在登录过程中不检索电子邮件

sql-server - 如何对总数求和但只保留多个名字中的一个

mysql - 带有连接的慢查询