MySQL DELETE FROM with UNION subquery by IN condition(通过 IN 条件使用 UNION 子查询的 MySQL DELETE FROM)
问题描述
我遇到了一个奇怪的 SQL 错误.最后一个查询不起作用.当然我可以把那个 DELETE 分成三个查询,但是我真的很奇怪为什么 MySQL 不允许我这样做.
I have tripped up on a curious SQL error. The last query doesn't work. Of course I can just split that DELETE into three queries, but I really wonder why MySQL doesn't let me do it this way.
一个小例子:
(SELECT id FROM stairs WHERE building = 123)
UNION
(SELECT id FROM lift WHERE building = 123)
UNION
(SELECT id FROM qrcodeid WHERE building = 123)
有效!
DELETE FROM startpoint WHERE id IN (SELECT id FROM stairs WHERE building = 123)
也有效!
而
DELETE FROM startpoint WHERE id IN (
(SELECT id FROM stairs WHERE building = 123)
UNION
(SELECT id FROM lift WHERE building = 123)
UNION
(SELECT id FROM qrcodeid WHERE building = 123)
)
引发错误
#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的UNION (SELECT id FROM lift WHERE building = 123) UNION (SELECT id FROM qrc"附近使用正确的语法
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT id FROM lift WHERE building = 123) UNION (SELECT id FROM qrc' at line 3
有人知道吗?
推荐答案
试试这个版本:
DELETE FROM startpoint
WHERE id IN (select *
from ((SELECT id FROM stairs WHERE building = 123)
UNION
(SELECT id FROM lift WHERE building = 123)
UNION
(SELECT id FROM qrcodeid WHERE building = 123)
)
我认为这个问题是子查询定义的一个神秘问题.子查询是 select 语句,而 union 是 select 语句的结合.
I think the issue is an arcane issue with the definition of a subquery. A subquery is a select statement, whereas a union is a conjunction of select statements.
实际上,如果您想要效率,您根本不会使用这种方法.我只是想展示如何修复错误.更好的解决方案是:
Actually, if you want efficiency, you wouldn't use this approach at all. I was just trying to show how to fix the error. A better solution would be:
DELETE sp FROM startpoint sp
WHERE EXISTS (select 1 from stairs s where s.building = 123 and s.id = sp.id) or
EXISTS (select 1 from lift l where l.building = 123 and l.id = sp.id) or
EXISTS (select 1 from qrcodeid q where q.building = 123 and q.id = sp.id);
建议在 stairs(id, building)、lift(id, building) 和 qrcodeid(id, building) 上使用索引.
Indexes are recommended on stairs(id, building), lift(id, building), and qrcodeid(id, building).
这篇关于通过 IN 条件使用 UNION 子查询的 MySQL DELETE FROM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 IN 条件使用 UNION 子查询的 MySQL DELETE FROM
基础教程推荐
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
