如何才能获得只有1名成员的团体人数?

时间:2011-04-13 16:46:21

标签: mysql

我正在尝试

select count(*)
  from groups
  left join members on groups.id=members.group_id
 group by groups.id
having count(members.id)=1

但它只给了我一堆1。我怎样才能获得行数?

2 个答案:

答案 0 :(得分:2)

只需将查询结果嵌入为子查询,即可计算查询结果。

作为旁注,内部联接比查询的外部联接更合适。实际上,如果members表中存在无效的group_id值,则只需要连接。

使用内部联接:

select count(*)
from
(
  select groups.id
  from groups 
  inner join members on groups.id=members.group_id
  group by groups.id
  having count(members.id)=1
) as sub

没有加入(假设没有孤儿):

select count(*)
from
(
  select group_id
  from members
  group_id
  having count(*) = 1
) as sub

答案 1 :(得分:1)

您要求每个组有1名成员的人数。所以一堆是正确的。您可以尝试使用像......这样的子查询。

SELECT COUNT(*) FROM (
  select count(*)
    from groups
    left join members on groups.id=members.group_id
   group by groups.id
  having count(members.id)=1
)