【问题标题】:SIngle Query from Multiple Table MySql来自多个表 MySql 的单个查询
【发布时间】:2019-07-06 20:41:33
【问题描述】:

我有包含相同字段的表格,例如:

p_central_ticket        p_south_ticket             p_west_ticket 
=====================================================================
- t_id                  - t_id                     - t_id
- t_open_by             - t_open_by                - t_open_by 
- t_closed_by           - t_closed_by              - t_closed_by 
- t_open_time           - t_open_time              - t_open_time 
- t_closed_time         - t_closed_time            - t_closed_time

我期望的一件事是这样的输出,但绝对是在单个查询中上面的 3 个表:

Name                today      weekly     monthly     yearly     
=================================================================   
test1@random.com         2           10          70        1000         
test2@random.com         5           14          60        1234

但是,我现在的查询只是为了计算 1 个表。

SELECT t_closed_by As Username, ixt_user_type.user_owner As Role,
    COUNT( case when t_closed_time > curdate() - interval 1 day THEN 1 END ) as today,
    COUNT( case when t_closed_time > curdate() - interval 7 day THEN 1 END ) as weekly,
    COUNT( case when t_closed_time > curdate() - interval 1 month THEN 1 END ) as monthly,
    COUNT( case when t_closed_time > curdate() - interval 1 year THEN 1 END ) as yearly
FROM p_central_ticket
LEFT JOIN m_event_type ON p_central_ticket.t_req_type = m_event_type.ev_type
LEFT JOIN ixt_user_type ON m_event_type.ev_user_type_target = ixt_user_type.user_type
WHERE t_status = 9
GROUP BY t_closed_by;

我的问题是,我应该怎么做,让我的查询从 3 个表计算但在单个查询中?

【问题讨论】:

    标签: mysql sql database database-design relational-database


    【解决方案1】:

    您可以使用 UNION 合并三个表并将所有连接应用到该合并表上,如下所示 -

    SELECT t_closed_by As Username, ixt_user_type.user_owner As Role,
        COUNT( case when t_closed_time > curdate() - interval 1 day THEN 1 END ) as today,
        COUNT( case when t_closed_time > curdate() - interval 7 day THEN 1 END ) as weekly,
        COUNT( case when t_closed_time > curdate() - interval 1 month THEN 1 END ) as monthly,
        COUNT( case when t_closed_time > curdate() - interval 1 year THEN 1 END ) as yearly
    FROM 
    ( select * from p_central_ticket 
      union 
      select * from p_south_ticket 
      union 
      select * from p_west_ticket
    )A 
    LEFT JOIN m_event_type ON A.t_req_type = m_event_type.ev_type
    LEFT JOIN ixt_user_type ON m_event_type.ev_user_type_target = ixt_user_type.user_type
    WHERE t_status = 9
    GROUP BY t_closed_by
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多