如何在两个表之间创建正确的连接?

时间:2015-03-24 10:20:02

标签: sql views sql-view

我有两个表,我想从两个表中获取数据。

为CustomerDetails

Id Customer1 Customer2
1  1         2
2  2         1
3  1         3

CustomerName

Id Name
1  a
2  b
3  c

输出应该是

Id Customer1 Customer2
1   a         b
2   b         a
3   a         c

我尝试使用内连接,但它只适用于一列而不适用于两者。

如何从SQL查询中获取此数据。

请帮我找到。

由于

3 个答案:

答案 0 :(得分:1)

使用 2 join s

select t1.id,t2.name customer1 ,t3.name customer2
from customerdetail t1 
join customername t2 on t1.customer1=t2.id
join customername t3 on t1.customer2=t3.id

答案 1 :(得分:0)

SELECT Id,
       CN1.Name AS Name1,
       CN2.Name AS Name2
FROM   CustomerDetails CD
       JOIN CustomerName AS CN1
            ON CD.Customer1 = CN1.ID
       JOIN CustomerName AS CN2
            ON CD.Customer2 = CN2.ID

我会用LEFT JOIN来做,因为它会更安全。我不知道您是否始终拥有Customer1Customer2

的值

答案 2 :(得分:0)

这应该是有效的:

SELECT CD.Id,
   CN1.Customer1,
   CN2.Customer2
FROM   CustomerDetails CD
   JOIN CustomerName AS CN1
        ON CD.Customer1 = CN1.ID
   JOIN CustomerName AS CN2
        ON CD.Customer2 = CN2.ID