简体   繁体   English

MySQL子查询WHERE IN,但也可以从IN子查询中获取其他列

[英]MySQL SubQuery WHERE IN, but also get additional column from IN subquery

This is slipping my mind at the moment, so let's say I have this code: 目前,这让我无所适从,所以让我说一下这段代码:

SELECT * FROM Table1
    WHERE (FoundCity, FoundState) IN
    ( SELECT city, state, distance
      FROM Table2
    ) ;

How do I also get it to pull the distance column above into the 'main' query? 我还如何将上面的distance列拖入“ main”查询中?

SELECT * FROM Table1 as T1
LEFT JOIN Table2 as T2 on T1.FoundCity = T2.FoundCity AND T1.FoundState = T2.FoundState 

Better idea would be to use Left join. 更好的主意是使用左连接。 And in * you can include column names you desire using T1 as prefix for columns from table 1 and T2 for table 2. (ex: T2.state) 在*中,您可以使用T1作为表1的列的前缀,并使用T2作为表2的列的前缀,包括所需的列名。(例如:T2.state)

Change the subquery to a join. 将子查询更改为联接。 You can then select any of the columns from either table. 然后,您可以从任一表中选择任何列。

SELECT *,  t2.distance
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.FoundCity = t2.city AND t1.FoundState = t2.state

Edit 编辑

If you want to keep the Tuple join syntax, you can also do: 如果要保留Tuple连接语法,还可以执行以下操作:

SELECT t1.*, t2.distance
    FROM t1 INNER JOIN t2
    ON (t1.FoundCity, t1.FoundState) = (t2.city, t2.state);

SqlFiddle SqlFiddle

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

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