【问题标题】:How to query using left join to get the result如何使用左连接查询得到结果
【发布时间】:2017-03-30 18:07:45
【问题描述】:

我正在处理 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

我希望业务表中的所有行以及订单表中 2017 年 3 月 30 日每个业务的每个订单状态的计数按总计排序。 结果集是:

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

请帮我查询得到上述结果。

【问题讨论】:

    标签: mysql join


    【解决方案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

    【讨论】:

    • "2017 年 3 月 30 日每个商家的每个订单状态的计数"
    • 。 .我想对答案投赞成票(尽管不喜欢缩进风格;),但它并没有完全回答问题。
    • 谢谢@GurV,但对我来说,该列表显示了订单表和业务表中的企业数量,并非所有企业都在列出,只有一行是升序的企业 ID,计数为 0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多