我有包含相同字段的表,例如:
p_central_ticket p_south_ticket p_west_ticket
=====================================================================
- t_id - t_id - t_id
- t_req_type - t_req_type - t_req_type
- t_status - t_status - t_status
我有一张桌子:
m_event_type
=============
- ev_type
- ev_activity
我当前的查询:
SELECT ev_activity AS Activity, COUNT( * ) AS Total
FROM m_event_type
LEFT JOIN p_central_ticket ON p_central_ticket.t_req_type = m_event_type.ev_type
WHERE t_status =9
GROUP BY ev_activity
上面查询的输出:
我的问题是,如果我想从上述3个表中总计,我该怎么办。
(例如,活动更改请求总数为18000,从 p_central_ticket + p_south_ticket + p_west_ticket)等。
谢谢...
答案 0 :(得分:1)
在子查询中使用union all
,然后将其加入:
select t1.ev_Activity, count(t1.*) as total
from m_event_type t1
LEFT JOIN
(
select *
from p_central_ticket
WHERE t_status =9
union all
select *
from p_south_ticket
WHERE t_status =9
union all
select *
from p_west_ticket
WHERE t_status =9
) t2
ON t2.t_req_type = t1.ev_type
GROUP BY t1.ev_activity
答案 1 :(得分:1)
使用UNION ALL(以避免删除重复项),然后对数量求和 请注意,如果您的表具有不同的列名,则只需要在选择中使用别名即可。
SELECT ev_activity AS Activity, SUM(quantity) AS Total
FROM m_event_type met
LEFT JOIN (SELECT c.t_req_type, COUNT(*) as quantity
FROM p_central_ticket c
WHERE c.t_status =9
GROUP BY c.t_req_type
UNION ALL
SELECT s.t_req_type, COUNT(*)
FROM p_south_ticket s
WHERE s.t_status =9
GROUP BY s.t_req_type
UNION ALL
SELECT w.t_req_type, COUNT(*)
FROM p_west_ticket w
WHERE w.t_status =9
GROUP BY w.t_req_type) p ON
p.t_req_type = met.ev_type
GROUP BY ev_activity
答案 2 :(得分:0)
您可以使用UNION ALL来选择3个表的所有行
startup;