1

これらの 2 つのテーブルを考慮すると、次のようになります。

テーブルオーダー:

    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

JOINテーブルUsersを2回:

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 APPLY の使用 -

    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 に答える