简体   繁体   中英

Multiple condition with sub-query

I have the following query:

SELECT * FROM a WHERE
     cityid IN (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM