MySQL select 条件值相同的前几行

MySQL select top rows with same condition values

我不知道如何给这个问题起标题。如果你有更好的词,请指正我。

我有两个表,Users 和 Posts。

用户:

id | username | password | ...

帖子数:

id | author_id | title | content | ...

现在我想列出 "most active" 位用户 - 发表帖子最多的用户。具体来说,我想要 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;

我能得到预期的结果。但是,如果某些用户的帖子数量相同,排名可能会“公平”。

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

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

在这里,实际上还有几个用户有 4 个帖子。

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

试试这个:

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;

可能不是最好的解决方案

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

我认为这是正确的解决方案:您需要子查询才能知道 post 在您的前十名中有多少排在第 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