mysql自联接返回空值

时间:2016-12-31 14:41:50

标签: mysql self-join

我有以下mysql查询

select a.agency_name, a.green ,b.red, c.amber
from (select count(action_status) as green, agency_name from tbl_actions
where action_status='In Progress' group by agency_name) a
join (select count(action_status) as red, agency_name from tbl_actions
where action_status='Delayed' group by agency_name) b on a.agency_name=b.agency_name
join (select count(action_status) as amber, agency_name from tbl_actions
where act_status='Completed' group by agency_name) c on a.agency_name=c.agency_name

并返回空白值 blank values

我确实在db中填充了相关数据的这些字段。

1 个答案:

答案 0 :(得分:2)

条件聚合更简单:

select a.agency_name,
       sum(a.action_status = 'In Progress') as green,
       sum(a.action_status = 'Delayed') as red,
       sum(a.action_status = 'completed') as amber
from tbl_actions a
group by a.agency_name;

不需要自我加入。您在结果集中没有获得任何行的原因是因为没有代理商拥有所有这三种状态。