无法选择具有案例条件的计数

时间:2015-04-01 07:49:01

标签: php mysql database

我有两张桌子:

user_groups

id    name    created_user
1     gn1     3
2     gn2     3

user_group_has_users

group_id    user_id
2           5
2           6

我想计算每组的用户数和类似的输出:

id    name    user_count
2     gn2     2
1     gn1     0

我试过了这个查询

select g.*,
       count(cg.user_id) as user_count
from user_groups as g
left join user_group_has_users as cg on cg.user_group_id = g.id
where g.created_user = 3

但它只返回一行。我不明白为什么会这样。 请帮帮我。

3 个答案:

答案 0 :(得分:0)

左连接,其中条件只是内部连接。你可能想要

select 
ug.id,
ug.name,
count(ughu.user_id) as user_count 
from user_groups ug 
left join user_groups_has_users ughu on ughu.group_id = ug.id 
and ug.created_user = 3 
group by ug.id
order by user_count desc ;

如果您仍希望使用created_user = 3过滤数据,请使用内部联接并将条件移至where clause

答案 1 :(得分:0)

使用此查询

SELECT g.* ,COUNT(cg.user_id) AS user_count 
FROM user_groups g 
LEFT JOIN user_group_has_users cg ON cg.group_id = g.id 
WHERE  g.created_user = 3 
GROUP BY g.id 
ORDER BY user_count DESC ;

答案 2 :(得分:0)

小心聚合和JOIN。在某些情况下,数字会膨胀。

看看这是否适合你:

select  g.*, 
      ( SELECT  count(*)
            FROM  user_group_has_users
            WHERE  user_group_id = g.id 
      ) AS user_count
    from  user_groups as g
    where  g.created_user = 3