用户中的MySql选择,计数(*)和子查询<>评论关系

时间:2012-04-05 04:05:13

标签: mysql sql subquery aggregate-functions

我的任务是计算有评论次数的用户数量> X.

我的SQL查询如下所示:

SELECT users.id,
       users.display_name, 
       (SELECT COUNT(*) 
          FROM cms_comments 
         WHERE cms_comments.author_id = users.id) AS comments_count 
  FROM users 
HAVING comments_count > 150;

一切正常,它正确显示所有用户。但我需要查询以一行返回所有这些用户的数量。我不知道如何更改此查询以使其生成正确的数据。

2 个答案:

答案 0 :(得分:11)

我认为这就是你要找的东西:

select count(*) from (
    select u.id from users u
    join cms_comments c on u.id = c.author_id
    group by u.id
    having count(*) > 150
) final

答案 1 :(得分:3)

使用group by子句

SELECT users.id,
       users.display_name, 
       (SELECT COUNT(*) 
          FROM cms_comments 
         WHERE cms_comments.author_id = users.id) AS comments_count 
FROM users 
GROUP BY users.id, user.display_name
HAVING comments_count > 150;

这将为每个用户提供一个计数.id,users.display_name有一个commments_count> 150

关于获取最多更新问题的用户总数的评论,但如果您想要计算符合此条件的所有用户,请使用

SELECT COUNT(*) AS TotalNumberOfUsersMatchingCritera
FROM
(
    SELECT users.id,
           users.display_name, 
           (SELECT COUNT(*) 
              FROM cms_comments 
             WHERE cms_comments.author_id = users.id) AS comments_count 
    FROM users 
    GROUP BY users.id, user.display_name
    HAVING comments_count > 150;
) AS T