php – MySQL:查询带有关系的排行榜
作者:互联网
我知道这是一个热门话题,但我仍然没有找到我正在寻找的东西.我想查询一个表
BOOKS_READ
id
user_id
book_id
格式化已列出最多书籍的用户的排行榜.当用户阅读书籍时,与书籍ID和用户ID匹配的记录将被记录到books_read表中.
是否可以对此查询的结果进行排名,从1开始,并考虑关系?
SELECT user_id, COUNT(*) AS book_count
FROM books_read
GROUP BY user_id
ORDER BY book_count DESC LIMIT 10
如果出现平局,我想在结果中列出“=”符号.
例如,
rank user_id book_count
=1 30 121
=1 17 121
2 101 119
=3 11 104
=3 91 104
非常感谢您的帮助!我不介意使用PHP来处理其中的一些,但我对学习这些东西的直接SQL解决方案非常感兴趣:-)
解决方法:
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来解析关系.
<?php
$rank = 1;
while ($row = mysql_fetch_assoc($result)) {
$users = explode(',', $row['user_id'];
foreach ($users as $user) {
echo 'Rank: ' . $rank . ' ' . $user . "\n;
}
$rank++;
}
?>
标签:php,mysql,ranking,leaderboard 来源: https://codeday.me/bug/20190630/1337667.html