在同一行中使用不同的值两次获取相同的字段

时间:2012-11-17 15:01:43

标签: sql sql-server

考虑这两个表:

订单

    order_id owner_id client_id
    ---------------------------
    123      2        1
    124      1        2

用户

    user_id name
    ------------
    1       Bill
    2       John

我正在尝试获得以下结果:

    order_id owner_name client_name
    -------------------------------
    123      John       Bill
    124      Bill       John

什么是“最佳”查询?

谢谢!

3 个答案:

答案 0 :(得分:3)

select o.order_id, 
       ow.name as owner_name, 
       cl.name as client_name
from orders o
  join users ow on o.owner_id = ow.user_id
  join users cl on o.client_id = cl.user_id

答案 1 :(得分:2)

JOIN两次

Users

SELECT
  o.order_id,
  ow.name 'owner_name',
  cl.name 'client_name'
FROM Orders o
INNER JOIN users ow ON o.owner_id = ow.user_id
INNER JOIN users cl ON o.client_id = cl.user_id

SQL Fiddle Demo

答案 2 :(得分:0)

使用CROSS APPLYs -

    DECLARE @Orders TABLE(Order_Id INT,Owner_Id INT,Client_Id INT)
    INSERT INTO @Orders
    SELECT 123,2,1 UNION ALL
    SELECT 124,1,2

    SELECT * FROM @Orders;

    DECLARE @Users TABLE(UserId INT,Name VARCHAR(10))
    INSERT INTO @Users
    SELECT 1,'Bill' UNION ALL
    SELECT 2,'John'

    SELECT * FROM @Users;

    SELECT b.Order_Id
          ,a.Name AS Owner_Name
          ,c.Name AS Client_Name 
    FROM @Orders b
        CROSS APPLY (SELECT * FROM @Users) a
        CROSS APPLY (SELECT * FROM @Users) c
    WHERE a.UserId=b.Owner_Id
        AND c.UserId=b.Client_Id
    ORDER BY b.Order_Id