Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Select, Count(*) and SubQueries in Users<>Comments relations

I have a task to count the quantity of users having count of comments > X.

My SQL-query looks like this:

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;

Everything is ok, it shows all users correctly. But i need query to return the quantity of all these users with one row. I don't know how to change this query to make it produce correct data.

like image 621
WesternTune Avatar asked Apr 05 '12 04:04

WesternTune


People also ask

What does count (*) mean in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

How do you write a subquery in a SELECT statement?

A subquery-also referred to as an inner query or inner select-is a SELECT statement embedded within a data manipulation language (DML) statement or nested within another subquery. You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed.

How many subqueries can be nested in MySQL?

Up to 32 levels of nesting is possible, although the limit varies based on available memory and the complexity of other expressions in the query.

What is Subselect in MySQL?

SUBQUERY. In MySQL, a subquery is defined as a query used inside another query. In other words, subquery can be nested inside another query. It is also known as inner query and the query that contains the subquery (inner query) is known as outer query.


2 Answers

I think this is what you're looking for:

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
like image 91
Mosty Mostacho Avatar answered Nov 16 '22 01:11

Mosty Mostacho


Use the group by clause

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;

This will give you a count for each of the users.id, users.display_name having a commments_count > 150

as for your comment of getting the total number of users it's best to update your question but if you want a count of all users matching this criteria use

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
like image 41
Dan P Avatar answered Nov 16 '22 01:11

Dan P