MySQL select top rows with same condition values

喜你入骨 提交于 2019-12-30 06:27:09

问题


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?


回答1:


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



回答2:


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



回答3:


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;


来源:https://stackoverflow.com/questions/27739838/mysql-select-top-rows-with-same-condition-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!