sql语法、计数、分组依据和添加语句
我有一个像这样的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
这可能吗?我尝试了一些有条款,但似乎无法使其发挥作用。
I have a sql statement like this (using mysql 5.5.15):
select global_id, count(id) as group_count
from globals_lists
group by global_id
order by group_count desc;
and would like to modify it to support a subset with an in statement like this:
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;
I'll get as a result:
global_id group_count
3 15
5 12
but would like
global_id group_count
3 15
5 12
4 0
6 0
Is this possible? I tried a couple of having clauses but couldn't seem to get it working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来有点尴尬,但是怎么样?
It's a little awkward looking, but how about?
您可以添加包含所有所需值的表。要么是内联的,如下所示,要么是在临时表中。然后您可以使用
left join
来匹配行数。You could add a table with all desired values. Either inline, like below, or in a temporary table. Then you can use
left join
to match the number of rows.使用
COUNT(*)
而不是COUNT(id)
,这样即使没有,它也会返回一个计数(假设 4 & )。确实存在 6 个:Instead of
COUNT(id)
, useCOUNT(*)
so it will return a count even if there are none, assuming 4 & 6 do exist: