简体   繁体   中英

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.

Eg, 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?

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

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

Try this:

SELECT username, PostCount
FROM (SELECT username, PostCount, IF(@PostCount = @PostCount:=PostCount, @idx:=@idx+1, @Idx:=1) AS idx
      FROM (SELECT u.username, COUNT(p.id) AS PostCount 
            FROM Posts p
            INNER JOIN Users u ON u.id=p.author_id
            GROUP BY p.author_id 
           ) AS A, (SELECT @PostCount:=0, @Idx:=1) AS B
      ORDER BY PostCount DESC
     ) AS A
WHERE idx <= 10;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM