开发者

Can this this MySQL query (with subqueries) be optimized?

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 AN开发者_StackOverflow社区D condnum = 1
) AND aptid IN (
    SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 2 AND condnum = 1
) ORDER BY name ASC 


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 into apartmentunits.

(Note: haven't tested this, may require some tweaking...)

SELECT `unitid`, `name` FROM `apartmentunits` 
 WHERE `unitid` IN (
        SELECT `unitid` FROM `rentconditionsmap` r1, `rentconditionsmap` r2
         WHERE r1.`unitid` = r2.`unitid`
           AND r1.`rentcondid` = 4
           AND r1.`condnum` = 1
           AND r2.`rentcondid` = 2
           AND r2.`condnum` = 1)
 ORDER BY `name` ASC


SELECT a.`unitid`, 
       a.`name` 
FROM   apartmentunits a 
       INNER JOIN rentconditionsmap r 
       ON a.aptid = r.aptid
   AND
       r.rentcondid in (2,4)
   AND 
       r.condnum = 1
ORDER BY a.`name` 


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

Select `unitid`, `name` FROM apartmentunits au
INNER JOIN rentconditionsmap rcm1
USING (aptid)
INNER JOIN rentconditionsmap rcm2
USING (aptid)
WHERE rcm1.rentcondid = 4
AND rcm1.condnum = 1
AND rcm2.rendcondid = 2
AND rcm2.condnum = 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜