Search code examples
mysqlsqlselectsql-order-bylimit

MySQL select top rows with same condition values


I don't know how to title this problem. Correct me if you have better words.

I have two tables, Users and Posts.

Users:

id | username | password | ...

Posts:

id | author_id | title | content | ...

Now I want to list the "most active" users - the users who have written the most posts. And specifically, I want the top 10 result.

SELECT u.username, COUNT(p.id) AS count 
FROM Posts p, Users u
WHERE u.id=p.author_id
GROUP BY p.author_id 
ORDER BY count DESC
LIMIT 10;

I can get the expected result. However, the ranking may not be "fair" if some users have same number of posts.

E.g., I may get results like:

User 1  | 14
User 2  | 13
...
User 9  | 4
User 10 | 4

Here, there are actually several more users who have 4 posts.

So, the top 10 could be not exactly 10 results. How can I get a more "fair" result that contains extra rows of users who have 4 posts?


Solution

  • This is the right solution, I think: you need the subquery to know how much post has the 10th place in your top ten. Then, you use the outer query to extract the users with almost that postcount.

    SELECT u.username, COUNT(p.id) AS count 
    FROM Posts p
    JOIN Users u ON u.id = p.author_id
    GROUP BY p.author_id 
    HAVING COUNT(p.id) >= 
    (
        SELECT COUNT(p.id) AS count 
        FROM Posts p
        JOIN Users u ON u.id = p.author_id
        GROUP BY p.author_id 
        ORDER BY count DESC
        LIMIT 9, 1
    )
    ORDER BY count DESC