2

我遇到了一个奇怪的 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 服务器版本相对应的手册,以在第 3 行的“UNION (SELECT id FROM lift WHERE building = 123) UNION (SELECT id FROM qrc”附近使用正确的语法

任何人的线索?

4

2 回答 2

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语句,而 aunionselect语句的结合。

编辑:

实际上,如果你想要效率,你根本不会使用这种方法。我只是想展示如何修复错误。更好的解决方案是:

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)

于 2013-06-20T22:55:25.097 回答
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)
于 2013-06-20T22:56:06.893 回答