如何使SQL更有效率。只需要数

时间:2011-07-01 18:04:43

标签: mysql sql postgresql

我需要找到多少用户:

  1. 谁有一个或多个粉丝
  2. 谁有两个粉丝
  3. 谁有三个粉丝
  4. 这是我开发的sql来回答#1

      SELECT users.id, count(fans.id)
        FROM users 
        JOIN fans on users.id = fans.user_id
    GROUP BY users.id
      HAVING COUNT(fans.id) > 0
    

    上面的查询有效,但我得到所有用户记录,然后我正在计算数组的大小。当用户数量达到数千时,它的性能很糟糕。如何重构查询以便我只能获得用户数?

    我正在使用mysql,但我可能需要使用postgresql的另一个项目。

4 个答案:

答案 0 :(得分:2)

试试这个:

select usersWithOneOrMoreFans = sum( case when t.fan_count >= 1 then 1 else 0 end ) ,
       usersWithTwoFans       = sum( case when t.fan_count =  2 then 1 else 0 end ) ,
       usersWithThreeFans     = sum( case when t.fan_count =  3 then 1 else 0 end )
from ( select user_id as user_id   ,
              count(*) as fan_count ,
       from fans
       group by fans.user_id
     ) t

[编辑删除无意义的表格引用]

答案 1 :(得分:2)

子查询可以很好地完成。

Select 
  Count(user.id) 
from 
  Users 
Where 
  (Select Count(fans.id) from Fans where user_id = users.id) > 0

答案 2 :(得分:0)

select num_users_with_fans, num_users_with_two_fans,num_users_with_three_fans
from(
    select count(1) as num_users_with_fans
    from(
        select users.id, count(fans.id)
         from users join fans on users.id = fans.user_id
         group by users.id
         having count(fans.id) > 0
    )a
cross join(
    select users.id, count(fans.id) as num_users_with_two_fans
     from users join fans on users.id = fans.user_id
     group by users.id
     having count(fans.id)=2
)b
cross join(
    select users.id, count(fans.id) as num_users_with_three_fans
     from users join fans on users.id = fans.user_id
     group by users.id
     having count(fans.id)=3
)c

答案 3 :(得分:0)

这是我的:

 SELECT nfans, count(*) AS nusers FROM
     (SELECT count(fans.id) AS nfans FROM fans GROUP BY user_id) foo
 GROUP BY nfans

这将为您提供拥有“nfans”粉丝的“nusers”用户数。

如果要将输出剪辑为最多3个风扇:

 SELECT nfans, count(*) AS nusers FROM
     (SELECT least(3,count(fans.id)) AS nfans FROM fans GROUP BY user_id) foo
 GROUP BY nfans

在这种情况下,bin“nfans = 3”包含拥有3个或更多粉丝的用户数。