从第二个表中获取数据

时间:2017-11-13 13:06:53

标签: sql sql-server

我有2张桌子。

Table1有像

这样的列
ID int
FromAddress int
ToAddress int

Table2有像

这样的列
ID int
ZipCode int

2个表之间的连接基于FromAddress,ToAdress(来自表1)和表2中的ID

粗糙数据与表1相似

ID     FROMAddress    ToAddress
1      500            620

Roughdata与Table2相似

ID     ZipCode
500    69999
620    6501

我想输出

ID     FromZipCode     ToZipCode
1      69999           6501

我尝试像

一样进行查询
Select T1.ID, T2.ZipCode as FromZipCode, T2.ZipCode as ToZipCode
From Table1 T1 join Table2 T2 on T1.FromAddress = T1.ID and T1.ToAddress = T2.ID

但这没有给我任何结果。

2 个答案:

答案 0 :(得分:1)

尝试这样,你需要JOIN两次:

Select T1.ID
    ,T2.ZipCode as FromZipCode
    ,T22.ZipCode as ToZipCode
From Table1 T1
join Table2 T2
    on T1.FromAddress = T2.ID -- first JOIN to get the info for FromAddress
join Table2 T22 
    on T1.ToAddress = T22.ID -- second JOIN to get the info for ToAddress

答案 1 :(得分:0)

您可以加入表格两次以获得所需的数据:

SELECT T1.ID,
       T2.ZipCode AS FromZipCode,
       TT2.ZipCode AS ToZipCode --From the second Table2 (TT2)
From Table1 T1 JOIN Table2 T2 ON T1.FromAddress = T1.ID 
     JOIN Table2 TT2 ON T1.ToAddress = TT2.ID --Join Table2 for the second time with another alias