我正试图弄清楚如何使用mysql查询获取每个类别中的顶级用户: 我的用户表如下所示:
user_id,category_id ......和其他一些东西
我的投票表看起来像这样(每行是一个正面投票): reciever_id ......以及其他一些东西
我在想我需要首先通过user_id确定唯一的投票,如下所示:
reciever_id, votes
1 2
2 6
然后我可以通过票数来命令...... 然后从用户中选择users.whatever,distinct(category_id),(该查询)WHERE users_id = that_queries_user.id
无论如何,我可能显然对如何编写此查询感到困惑,任何帮助将不胜感激。
答案 0 :(得分:2)
这将为您返回前10位用户:
SELECT u.*,
(
SELECT COUNT(*)
FROM votes v
WHERE v.receiver_id = u.user_id
) AS score
FROM users u
ORDER BY
score DESC
LIMIT 10
这将为您返回每个类别中的一位顶级用户:
SELECT u.*
FROM (
SELECT DISTINCT category_id
FROM users
) uo
JOIN users u
ON u.user_id =
(
SELECT user_id
FROM users ui
WHERE ui.category_id = uo.category_id
ORDER BY
(
SELECT COUNT(*)
FROM votes v
WHERE v.receiver_id = ui.user_id
) DESC
LIMIT 1
)
答案 1 :(得分:0)
试试这个(如果你说的话,每一行都是一个正面投票):
Select User_id, category_id, Count(*) voteCnt
From Users u Join Votes v
On v.receiver_id = u.user_id
Group By User_id, category_id
Having Count(*) > [Whayever Threshold you want]
Order By Count(*) Desc
或者如果投票栏实际上是投票数:
Select User_id, category_id, Sum(votes) voteSum
From Users u Join Votes v
On v.receiver_id = u.user_id
Group By User_id, category_id
Having Sum(votes) > [Whayever Threshold you want]
Order By Sum(votes) Desc