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

x6yk4ghg  于 2023-01-29  发布在  SQL Server
关注(0)|答案(1)|浏览(157)

我想知道有没有一种简单的方法把这两张table连在一起。
表“表1":
| 姓名|来自国家ID|目的地国家ID|
| - ------|- ------|- ------|
| 萨姆|1个|第二章|
| 背风面|三个|四个|
| 约翰|第二章|1个|
| 果渣|零|三个|
表“表2":
| 国家ID|国家名称|
| - ------|- ------|
| 1个|美国|
| 第二章|联合 Realm |
| 三个|加拿大|
| 四个|尼泊尔|

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
zf9nrax1

zf9nrax11#

请尝试以下操作:

select t1.Name,t2.CountryName as FromCountry,t3.CountryName as ToCountry from [dbo].[Table1] t1
left join [dbo].[Table2] t2
on(t1.FromCountryID=t2.CountryID)
left join [dbo].[Table2] t3
on(t1.ToCountryID=t3.CountryID)

select t1.Name,t1.FromCountryID,t2.CountryName as FromCountry,t1.ToCountryID,t3.CountryName as ToCountry from [dbo].[Table1] t1
left join [dbo].[Table2] t2
on(t1.FromCountryID=t2.CountryID)
left join [dbo].[Table2] t3
on(t1.ToCountryID=t3.CountryID)

相关问题