sql语法,计数,分组依据和语句中添加

时间:2011-12-16 22:52:48

标签: sql count group-by

我有这样的sql语句(使用mysql 5.5.15):

select global_id, count(id) as group_count
from globals_lists
group by global_id
order by group_count desc;

并希望修改它以支持具有如下所示的in语句的子集:

select global_id, count(id) as group_count
from globals_lists
where global_id in (3,4,5,6)
group by global_id
order by group_count desc;

我会得到结果:

global_id   group_count
3           15 
5           12

但希望

global_id   group_count
3           15 
5           12
4           0
6           0

这可能吗?我尝试了几个条款,但似乎无法让它发挥作用。

3 个答案:

答案 0 :(得分:2)

看起来有点尴尬,但是怎么样?

select IDs.ID, ifnull(count(globals_lists.global_id),0) as group_count
from (select 3 as ID
             UNION select 4
             UNION select 5
             UNION select 6) as IDs
left join globals_lists on IDs.ID = globals_lists.global_id
group by IDs.ID
order by group_count desc;

答案 1 :(得分:1)

您可以添加包含所有所需值的表格。内联,如下,或临时表。然后,您可以使用left join来匹配行数。

select  lst.nr
,       count(gl.id) as group_count
from    (
        select 3 as nr
        union all select 4
        union all select 5
        union all select 6
        ) lst
left join 
        globals_lists gl
on      lst.nr = gl.global_id
group by 
        lst.nr
order by 
        count(gl.id) desc

答案 2 :(得分:0)

使用COUNT(id)代替COUNT(*),因此即使没有,也会返回计数,假设4& 6确实存在:

select global_id, count(*) as group_count
from globals_lists
where global_id in (3,4,5,6)
group by global_id
order by group_count desc;