如何使用左连接查询以获得结果

时间:2017-03-30 18:07:45

标签: mysql join

我正在研究mysql上的两个表,我试图从左表中获取所有行以及第二个表中与第一个表匹配的列。

商家

id | business_name
-------------------
1   |abc    
2   |def    
3   |ghi    
4   |jkl    
5   |mno

订单

business_id_fk  | order_status  | date 
----------------------------------------    
2               |  PCK         |  30-03-2017    
3               |  DEL         |  30-03-2017    
2               |  DEL         |  30-03-2017    
2               |  PCK         |  30-03-2017    
4               |  PCK         |  28-03-2017    
3               |  PCK         |  29-03-2017    
4               |  DEL         |  30-03-2017

我希望30-03-2017的每个业务的业务表中的所有行和每个订单状态的计数从订单表排序总计。 结果集是:

id | business_name | total(order_status) | count(PCK) | count(DEL) 
----------------------------------------------------
2  | def           | 3       | 2      |  1   
3  | ghi           | 1       | 0      |  1    
4  | jkl           | 1       | 0      |  1    
1  | abc           | 0       | 0      |  0    
5  | mno           | 0       | 0      |  0

请帮我查询以获得上述结果。

1 个答案:

答案 0 :(得分:1)

您可以在联接中使用条件聚合:

select b.id,
    b.business_name,
    count(o.order_status) as total_count,
    coalesce(sum(o.order_status = 'PCK'), 0) as count_PCK,
    coalesce(sum(o.order_status = 'DEL'), 0) as count_DEL
from business b
left join orders o on b.id = o.business_id_fk
    and o.date = '2017-03-30'
group by b.id,
    b.business_name;

我假设订单表上的日期列的数据类型为日期(或格式为YYYY-MM-DD的至少格式化字符串)。

Demo