MySQL选择具有相同条件值的顶行

时间:2015-01-02 09:19:27

标签: mysql sql select sql-order-by limit

我不知道如何标题这个问题。如果你有更好的话,请纠正我。

我有两个表,用户和帖子。

用户:

id | username | password | ...

文章:

id | author_id | title | content | ...

现在我想列出“最活跃”的用户 - 撰写帖子最多的用户。具体来说,我想要top 10结果。

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;

我可以得到预期的结果。但是,如果某些用户的帖子数相同,则排名可能不是“ fair ”。

例如,我可能得到如下结果:

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

此处,实际上还有几位用户拥有4个帖子。

因此,top 10可能不是10结果。如何获得更多“合理”结果,其中包含有4个帖子的额外用户行?

3 个答案:

答案 0 :(得分:5)

这是正确的解决方案,我认为:您需要子查询才能知道在前十名中有多少帖子排在第10位。然后,使用外部查询来提取几乎具有该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

答案 1 :(得分:3)

也许不是最好的解决方案

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

答案 2 :(得分:0)

试试这个:

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;