如何同时加入两个表?

时间:2016-01-25 09:35:19

标签: sql

Product

Id name     t1   t2
1  A        1    4
2  B        5    2
3  C        3    1
4  D        4    5

Tan

id  tan
1   tanA
2   tanB    
3   tanC
4   tanD
5   tanE

我有两个上面的表格,我希望结果如下所示,期望结果如何。

期待结果

A   tanA    tanD
B   tanE    tanB
C   tanC    tanA    
D   tanD    tanE

2 个答案:

答案 0 :(得分:2)

您可以加入多个表格:

SELECT p.Name AS ProductName,
       t1.tan AS Tan1,
       t2.tan AS Tan2
FROM dbo.Product p
INNER JOIN Tan t1
    ON p.t1 = t1.id
INNER JOIN Tan t2
    ON p.t2 = t2.id
ORDER BY ProductName ASC

Demo

答案 1 :(得分:0)

您可以使用表格别名从棕褐色表格中选择两次:

FROM Product INNER JOIN tan tan1 ON tan1.id = product.t1
             INNER JOIN tan tan2 ON tan2.id = product.t2

选择合适的列:

SELECT Product.name AS name, tan1.tan AS Tan_1, tan2.tan AS Tan_2

给予:

SELECT product.name AS name, tan1.tan AS Tan_1, tan2.tan AS Tan_2
FROM Product INNER JOIN tan tan1 ON tan1.id = product.t1
             INNER JOIN tan tan2 ON tan2.id = product.t2