mySQL在单个查询中多次使用相同的表/字段

时间:2013-07-16 10:14:42

标签: mysql

我在mySQL数据库中有两个表:

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)“customer_name”字段,结果如下所示:

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

这意味着在查询中使用相同的表2x 别名输出字段“customer_name”2x with  “customer_order_name”和“customer_from_name”。

它应该很简单,但我被卡住了。 任何帮助将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;

fiddle

相关问题