【问题标题】:group by count(*) mysql multiple tables按计数(*)mysql多个表分组
【发布时间】:2014-05-11 19:36:42
【问题描述】:

我试图对多个表进行计数(*),但将它们放在一个组中。

我在mysql中的查询是:

SELECT
  (SELECT COUNT(*) as 'Orders', Customer FROM table WHERE `date` = CURRENT_DATE()) as Client1, 
  (SELECT COUNT(*) as 'Orders', Customer FROM table2 WHERE `date` = CURRENT_DATE()) as Client2,
  (SELECT COUNT(*) as 'Orders', Customer FROM table3 WHERE `date` = CURRENT_DATE()) as Client3
  group by Customer

这就是我想要找回的:

+-------------+---------+---------+---------+
| Customer    | Client1 | Client2 | Client3 |
+-------------+---------+---------+---------+
| John Doe    | 88      | 19      | 0       |
+-------------+---------+---------+---------+
| Mary P      | 0       | 32      | 0       |
+-------------+---------+---------+---------+
| Scott K     | 11      | 25      | 31      |
+-------------+---------+---------+---------+

我唯一担心的是客户不会存在于其他表中,例如 - John Doe 只是 table1 中的客户 - 而不是 table2 或 table3。

与 Mary P 相同 - 她只是 table2 中的客户,而不是 table1 或 table 3 等。

【问题讨论】:

    标签: mysql


    【解决方案1】:
    select a.Customer, sum(client1), sum(client2), sum(client3)
    from
    (
        select Customer, count(*) as client1, 0 as client2, 0 as client3 from table WHERE `date` = CURRENT_DATE() group by Customer
        union all
        select Customer, 0, count(*), 0 from table2 WHERE `date` = CURRENT_DATE() group by Customer
        union all
        select Customer, 0, 0, count(*) from table3 WHERE `date` = CURRENT_DATE() group by Customer
    ) as a
    group by a.Customer
    

    【讨论】:

      【解决方案2】:

      请在 union all 前使用() 喜欢

        select a.Customer, sum(client1), sum(client2), sum(client3)
          from
          (
              (select Customer, count(*) as client1, 0 as client2, 0 as client3 from table WHERE `date` = CURRENT_DATE() group by Customer)
              union all
              (select Customer, 0, count(*), 0 from table2 WHERE `date` = CURRENT_DATE() group by Customer)
              union all
              (select Customer, 0, 0, count(*) from table3 WHERE `date` = CURRENT_DATE() group by Customer)
          ) as a
          group by a.Customer
      

      【讨论】:

        猜你喜欢
        • 2014-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多