我有包含相同字段的表,例如:
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个表中进行计算,但在单个查询中?
答案 0 :(得分:0)
您可以使用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