查询多个EXIST
我有一个房间和设备的数据库。我想查询数据库并返回带有电视、收音机、卫星和冰箱等房间的列表(eq1、eq2、eq3、...、eqN)。
我有以下 SELECT 语句:
select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
有什么方法可以优化或缩短它吗?
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).
I have the following SELECT statement:
select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
Is there any way to optimize or making this shorter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要缩短您可以
编辑
但不确定它是否真的会使其更快...恰恰相反,带有 EXISTS AND EXISTS 的版本有机会在第一个 false 上修剪执行分支,上面必须实际计算不同的值(遍历所有记录)并且看看那个值是什么。
所以你应该考虑什么更快:
这取决于你的数据统计(我会认为如果大多数房间没有所有所需的设备,那么您的初始版本应该更快,如果大多数房间都有所有设备,那么如果 EXISTS 版本更快,那么建议的版本可能会表现更好;首先是最有可能失败的查询,即首先检查最稀有的设备)
您也可以尝试使用 GROUP BY 的版本
(以上 SQL 未测试)
To shorten you could
EDIT
but not sure if it will actually make it faster... quite the opposite, the version with EXISTS AND EXISTS has a chance to prune execution branch on the first false, the above must actually count the distinct values (go through all records) and see what that value is.
So you should think what is faster:
It depends on the statistics of your data (I would think that if most rooms don't have all the sought equipment in them then your initial version should be faster, if most rooms have all equipment in them then the proposed version might perform better; also if the EXISTS version is faster make an effort to first the queries that are most likely to fail i.e. first check for rarest equipment)
You can also try a version with GROUP BY
(above SQL not tested)
试试这个(我没有任何数据库可用于测试它,还要考虑性能)
注意:2 - 这是您需要的选项数量。例如,它们是:“eq1”、“eq2”
try this (I don't have any DB available to test it, also consider performance )
Note: 2 - it is the number of options that you need. In example they are: 'eq1','eq2'
使用存储过程。
以下是 mysql 的过程:
执行方法:
CALL GetRooms('RoomTableName','EquipmentTableName','EquipmentIDs')
示例:
希望这会有所帮助。
Use an Stored Procedure.
here is the procedure for mysql:
Execute it with:
CALL GetRooms('RoomTableName','EquipmentTableName','EquipmentIDs')
Example:
Hope this helps.
要更快地执行查询,请使用 Exists
To Execute Query Faster use Exists