1

这个问题还有意义吗?

我正在尝试做一个查询,它从同一张表上的 JOIN 中提取 2 个不同的值。

我有和“Order”,其中有两个值,“TakenBy”和“PackedBy”这些是来自员工表的 User_ID。大多数情况下,它们不会相同。

如何在查询中分隔它们?我可以得到其中一个,但我不确定如何重新获取这两个值。

这是我要得到的东西..

SELECT
O.Order_ID AS OID, Customer_ID AS CID, Emp.UserName AS UserName
FROM Orders O
LEFT JOIN Employees Emp ON Emp.User_ID = O.User_ID
WHERE O.Customer_ID =3

但是,当我想要“PackedBy”时呢?我也怎么得到呢?

[Employees Table]
[User_ID] [UserName]
[1]       [Joe]
[2]       [Bill]
[3]       [Bobby]
[4]       [Steve]

[Orders]
[Order_ID] [Customer_ID] [TakenBy] [PackedBy]
[10]       [55]          [3]       [1]
[11]       [66]          [2]       [4]
[12]       [77]          [3]       [4]
[13]       [88]          [2]       [1]

我希望查询返回类似

[OID]   [CID]   [TAKER] [PACKER]
[11]    [66]    [Bill]  [Steve]
4

2 回答 2

2

如果您使用不同的表别名,您可以多次加入同一个表。

例如:

SELECT
O.Order_ID AS OID, Customer_ID AS CID, 
   EmpP.UserName AS Packer,
   EmpT.UserName AS Taker

FROM Orders O
LEFT JOIN Employees EmpP ON Emp.User_ID = O.PackedBy
LEFT JOIN Employees EmpT ON Emp.User_ID = O.TakenBy
WHERE O.Customer_ID =3
于 2012-08-19T20:59:57.777 回答
1

您需要两个联接,一个用于每个员工角色:

SELECT O.Order_ID AS OID, Customer_ID AS CID, Emp.UserName AS UserName,
       packed.UserName as PackedBy
FROM Orders O LEFT JOIN
     Employees Emp
     ON Emp.User_ID = O.User_ID left join
     Employees Packed
     on Packed.User_id = o.PackedBy
WHERE O.Customer_ID =3
于 2012-08-19T21:00:06.373 回答