这个 MySQL 查询(带有子查询)可以优化吗?
有没有更好的方法让这个查询工作?我正在寻找一种更有效的解决方案(如果有的话)。
SELECT `unitid`, `name` FROM apartmentunits WHERE aptid IN (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 4 AND condnum = 1
) AND aptid IN (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 2 AND condnum = 1
) ORDER BY name ASC
Is there any better way to make this query work? I'm looking for a more efficient solution, if there is one available.
SELECT `unitid`, `name` FROM apartmentunits WHERE aptid IN (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 4 AND condnum = 1
) AND aptid IN (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 2 AND condnum = 1
) ORDER BY name ASC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你想在这里自我加入。将表
rentconditionsmap
连接到其自身,并指示连接两侧的条件。然后将该查询的结果加入到apartmentunits
中。(注意:尚未测试过,可能需要一些调整......)
I think you want a self-join here. Join table
rentconditionsmap
to itself, and indicate the conditions on either side of the join. Then join the results of that query intoapartmentunits
.(Note: haven't tested this, may require some tweaking...)
是的,使用联接。大多数 DBMS 都会优化连接,这样它就不需要拉出它不需要的行。 MySQL 仍然使用嵌套循环,但我相信 Oracle 会使用散列连接。
所以这个查询可能更好地表达为
Yes, using joins. Most DBMSes will optimise the join such that it need not pull rows it doesn't have to. MySQL still uses nested loops, but I belive Oracle will use hash joins.
So this query might better be expressed as