15

我的任务是计算评论数 > 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;

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

4

2 回答 2

15

我想这就是你要找的:

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
于 2012-04-05T04:26:44.657 回答
10

使用 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;

这将为您计算每个 users.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
于 2012-04-05T04:16:16.290 回答