简体   繁体   English

带子查询的多条件

[英]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?有没有办法(使用 MySQL 语法)避免运行子查询 3 次?

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.我认为这是错误的,因为所有的行a将与上述显示。

The correct way is I think KarlsFriend's one, or this正确的方法是我认为 KarlsFriend 的一个,或者这个

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.但是无论您使用哪种方式,即使是您原来的方式,我认为查询计划不会包括运行子查询(SELECT id FROM b) 3 次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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