1

考虑这两个表:

订单

    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

什么是“最佳”查询?

谢谢!

4

3 回答 3

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
于 2012-11-17T15:03:33.290 回答
2

JOINUsers两次:

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 小提琴演示

于 2012-11-17T15:03:38.230 回答
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
于 2012-11-17T17:22:36.773 回答