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

How To create correct Join between two tables?

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

客户详情

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 查询中获取这些数据。

请帮我找到这个。

谢谢

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 joins

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

这应该是工作:

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