使用两个JOINS或两个ON从同一个表中查询相同的值

时间:2012-08-19 20:54:33

标签: mysql

这个问题是否有意义?

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

我有和“订单”有两个值,“TakenBy”& “PackedBy”这些是Employees表中的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]

我希望Query返回类似

的内容
[OID]   [CID]   [TAKER] [PACKER]
[11]    [66]    [Bill]  [Steve]

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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