mysql按条件删除in,MySQL在IN条件下使用UNION子查询删除

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.

A little example:

(SELECT id FROM stairs WHERE building = 123)

UNION

(SELECT id FROM lift WHERE building = 123)

UNION

(SELECT id FROM qrcodeid WHERE building = 123)

works!

DELETE FROM startpoint WHERE id IN (SELECT id FROM stairs WHERE building = 123)

works, too!

Whereas

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)

)

raises the error

#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

Anyone a clue?

解决方案

Try this version instead:

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)

)

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.

EDIT:

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);

Indexes are recommended on stairs(id, building), lift(id, building), and qrcodeid(id, building).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值