用来自不同表的数据引用两列

时间:2019-06-03 14:45:54

标签: sql sql-server

我在执行SQL作业时遇到麻烦。我正在使用Microsoft SQL Server Management Studio17。在我的表中,有一个CustomerID1和CustomerID2列。我想将ID与另一个称为Customer的表连接,并将ID作为主键和全名。我想要的输出是Customer1Name和Customer2Name。如何连接两个桌子?

select c.FullName from Sales s, Customer c where s.CustomerID1 = c.Id

select c.FullName from Sales s, Customer c where s.CustomerID2 = c.Id

这是我正在尝试做的事情,但我希望如果可能的话,请用一句话表示。预先感谢!

1 个答案:

答案 0 :(得分:2)

尝试以下操作:

select c1.FullName as Customer1Name, c2.FullName as Customer2Name
from Sales s
left join Customer c1 
on s.CustomerID1 = c1.Id 
left join Customer c2 
on s.CustomerID2 = c2.Id