我惹恼了一个好奇的SQL错误。最后一个查询不起作用。当然,我可以将DELETE分成三个查询,但我真的很想知道MySQL为什么不让我这样做。
一个小例子:
(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服务器版本对应的手册,以便在UNION(SELECT id FROM lift WHERE building = 123)附近使用正确的语法UNION(SELECT id FROM qrc' at line 3
任何人都有线索?
答案 0 :(得分:2)
请尝试使用此版本:
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
语句的组合。
编辑:
实际上,如果你想要效率,你根本不会使用这种方法。我只是想说明如何修复错误。更好的解决方案是:
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)
上建立索引。
答案 1 :(得分:2)
试试那个SQL
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)