问题描述
我知道这是一个受欢迎的话题,但是我仍然找不到想要的东西.我想查询一张桌子
I know this is a popular topic, but I still haven't found quite what I'm looking for. I'd like to query one table
BOOKS_READ
id
user_id
book_id
格式化列出阅读最多书籍的用户排行榜.当用户阅读一本书时,与该书ID和用户ID相匹配的记录将被记录到books_read表中.
to format a leaderboard of users who have listed the most books as having been read. When a user reads a book, a record matching the book id and the user id gets logged into the books_read table.
是否可以从1开始并考虑平局来对查询结果进行排名?
Is it possible to rank the results of this query, starting at 1, and with consideration of ties?
SELECT user_id, COUNT(*) AS book_count
FROM books_read
GROUP BY user_id
ORDER BY book_count DESC LIMIT 10
如果出现平局,我想在结果中列出一个'='符号.
In the event of a tie, I would like to list an '=' sign in the results.
例如,
rank user_id book_count
=1 30 121
=1 17 121
2 101 119
=3 11 104
=3 91 104
非常感谢您的帮助!我不介意使用PHP来处理其中的一些问题,但是我对学习针对此类问题的直接SQL解决方案非常感兴趣:-)
Many thanks for any help! I don't mind using PHP to handle some of it, but I'm very interested in learning straight SQL solutions to these kinds of things :-)
推荐答案
SELECT GROUP_CONCAT(user_id, book_count
FROM (
SELECT user_id, COUNT(*) AS book_count
FROM books_read
GROUP BY user_id
ORDER BY book_count DESC
) AS T1
GROUP BY book_count
ORDER BY book_count
给你
user_id book_count
30,17 121
101 119
11,91 104
然后您可以使用PHP解析关系.
Which you can then use PHP to parse for ties.
<?php
$rank = 1;
while ($row = mysql_fetch_assoc($result)) {
$users = explode(',', $row['user_id'];
foreach ($users as $user) {
echo 'Rank: ' . $rank . ' ' . $user . "\n;
}
$rank++;
}
?>
这篇关于MySQL:查询有关系的排行榜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!