来自多个 Table MySql 的单个查询

SIngle Query from Multiple Table MySql

我有 table 个包含相同的字段,例如:

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 table:

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

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

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 table 秒开始计算,但在单个查询中?

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

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