Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
mrmoment Avatar asked Jan 02 '15 09:01

mrmoment


2 Answers

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
like image 67
Alessandro Lai Avatar answered Sep 24 '22 07:09

Alessandro Lai


Maybe not the best solution

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) in 
(
    SELECT COUNT(p.id)
    FROM Posts p
    join Users u on u.id = p.author_id
    GROUP BY p.author_id 
    ORDER BY count DESC
    LIMIT 10    
)
ORDER BY count DESC
like image 31
juergen d Avatar answered Sep 26 '22 07:09

juergen d