如何从具有公共列的两个不同表中查找公共值

时间:2017-07-21 14:32:46

标签: sql

我有两个表table1和table2。两个表都有一个名为city的公共列。 如何在两个表中找到城市下的所有值?

2 个答案:

答案 0 :(得分:0)

您可以在城市列上执行inner join,以查找两个表中都存在的值。

select
    -- Output the city from either table (since it will be the same)
    t1.city 
from
    -- Join table1 and table2 together, on a matching city column
    table1 t1 join table2 t2 on (t1.city=t2.city)
group by 
    -- Only return a single row per city
    t1.city

答案 1 :(得分:0)

SELECT tbone.desired_column1
       tbone.desired_column2,
       --other columns from table one
       tbtwo.desired_column1,
       tbtwo.desired_column2
       --other columns from table two
 -- Bellow we're stating what this table could be identified as (tbone and tbtwo), so that you don't have to keep typing table name above and bellow. Can be anything, such as A or B or HORSECORRECTINGBATTERY
 FROM table1 tbone,  
      table2 tbtwo
 WHERE tbone.city = tbtwo.city

如果您不想指定要采用的列,请使用

SELECT * FROM ...