0

mySQL データベースに 2 つのテーブルがあります。

customers
============
customer_id (1, 2 )
customer_name (john, mark)


orders
============
order_id = 123
customer_id = 1
customer_from_id = 2

アイデアは、顧客テーブルに参加する注文テーブルで単一のクエリを実行することです。

orders.customer_id = customers.customer_id 
orders.customer_from_id = customers.customer_id

2 つのテーブルを結合して「customer_name」を取得します。

では、「注文」に対して単一のクエリを実行し、すべての (2) 「customer_name」フィールドを展開して、結果が次のようになるようにするにはどうすればよいですか。

+--------+------------+---------------------+------------------+---------------------+
order_id  customer_id   customer_order_name   customer_from_id   customer_from_name
+--------+------------+---------------------+------------------+---------------------+
   123       1                  john                  2                 mark  
+--------+------------+---------------------+------------------+---------------------+

これは、クエリで同じテーブルを 2 回使用し、出力フィールド「customer_name」を「customer_order_name」と「customer_from_name」で 2 回エイリアスすることを意味します。

それは簡単ですが、私は立ち往生しています。どんな助けでも大歓迎です。

ありがとうございました。

4

2 に答える 2

1

2 回参加し、プレフィックスを使用してエイリアスを指定します。

select order_id, buyer.customer_id, buyer.customer_name, seller.customer_id as customer_from_id, seller.customer_name as customer_from_name from orders o
join customers seller on o.customer_from_id = seller.customer_id
join customers buyer on o.customer_id = buyer.customer_id;
于 2013-07-16T10:20:05.730 に答える
0
select order_id,  c1.customer_id as customer_id,
c1.customer_name as customer_order_name ,
c2.customer_id as customer_from_id,
c2.customer_name as customer_from_name
from orders o
left join customers c1 using (customer_id)
left join customers c2 on o.customer_from_id = c2.customer_id;

フィドル

于 2013-07-16T10:24:38.980 に答える