开发者

Multiple condition with sub-query

I have the following query:

SELECT * FROM a WHERE
     cityid I开发者_如何学运维N (SELECT id FROM b)
  OR regionid IN (SELECT id FROM b)
  OR countryid IN (SELECT id FROM b)

Is there a way (using MySQL syntax) to avoid running the sub-query 3 times?


Instead of using subselects a join might be used

SELECT a.* FROM a 
   LEFT OUTER JOIN b 
       ON (a.cityid = b.id OR a.regionid = b.id or a.countryid = b.id) 
WHERE b.id IS NOT NULL


Updated:

1st try was:

SELECT a.*
FROM a 
  LEFT JOIN b AS city 
    ON a.cityid = city.id
  LEFT JOIN b AS region
    ON a.regionid = region.id
  LEFT JOIN b AS country 
    ON a.countryid = country.id

which I think it's wrong because all rows of a will be shown with the above.

The correct way is I think KarlsFriend's one, or this

2nd try:

SELECT a.*
FROM a 
  INNER JOIN b 
    ON ( a.cityid = b.id OR a.regionid = b.id or a.countryid = b.id )  

But either way you use, even your original one, I don't think that the query plan will include running the subquery (SELECT id FROM b) 3 times.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜