SQL Server将表的ID与另一个表的主键列连接成两列

时间:2016-12-27 08:20:50

标签: sql-server join

我想知道是否有一种简单的方法可以加入这两个表格。

表1

Name FromCountryID ToCountryID
------------------------------
sam         1          2    
lee         3          4
john        2          1

表2

CountryID   CountryName
1           USA
2           UK
3           Canada
4           Nepal

2 个答案:

答案 0 :(得分:1)

您需要使用不同的别名

连接同一个表两次
select t1.name, 
       fromTab.countryName as FromCountry,
       toTab.countryName as ToCountry
from table1 t1
left join table2 fromTab on fromTab.countryId = t1.fromCountryId
left join table2 toTab on toTab.countryId = t1.toCountryId

答案 1 :(得分:0)

 SELECT * FROM  Table1 INNER JOIN Table2 ON Table2.CountryID = Table1.FromCountryID