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

通过 JOIN(ing) 两个表获取“customer_name”。

那么我如何对“订单”进行单一查询并展开所有(2)“客户名称”字段,结果如下所示:

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

这意味着在查询中使用相同的表 2x 并将输出字段“customer_name”2x 与“customer_order_name”和“customer_from_name”混为一谈。

这应该很简单,但我被卡住了。任何帮助将非常感激。

谢谢你。

4

2 回答 2

1

加入两次并使用前缀并给出别名:

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 回答