我有评论表,其中存储了所有内容,我必须对所有内容进行SUM并添加BEST ANSWER * 10。 我需要整个列表的排名,以及如何显示指定用户/ ID的排名。
这是SQL:
SELECT m.member_id AS member_id,
(SUM(c.vote_value) + SUM(c.best)*10) AS total
FROM comments c
LEFT JOIN members m ON c.author_id = m.member_id
GROUP BY c.author_id
ORDER BY total DESC
LIMIT {$sql_start}, 20
答案 0 :(得分:0)
这样的事情怎么样:
SET @rank=0;
SELECT * FROM (
SELECT @rank:=@rank+1 AS rank, m.member_id AS member_id,
(SUM(c.vote_value) + SUM(c.best)*10) AS total
FROM comments c
LEFT JOIN members m ON c.author_id = m.member_id
GROUP BY c.author_id
ORDER BY total DESC
) as sub
LIMIT {$sql_start}, 20
答案 1 :(得分:0)
如果您的MySQL版本支持,您可能需要查看windowing functions ...
SELECT m.member_id AS member_id,
(SUM(c.vote_value) + SUM(c.best)*10) AS total,
RANK() OVER (ORDER BY (SUM(c.vote_value) + SUM(c.best)*10)) as ranking
FROM comments c
LEFT JOIN members m ON c.author_id = m.member_id
GROUP BY c.author_id
ORDER BY total DESC;
另一种可能性是:
SELECT m.member_id AS member_id,
(SUM(c.vote_value) + SUM(c.best)*10) AS total,
(SELECT count(distinct <column you want to rank by>)
FROM comments c1
WHERE c1.author_id = m.member_id) as ranking
FROM comments c
LEFT JOIN members m ON c.author_id = m.member_id
GROUP BY c.author_id
ORDER BY total DESC;
注意:围绕这个有很多未解决的问题,但上述两种技术是确定排名的简单方法。你需要改变上面的内容以满足你的确切需要,因为我对member_id的排名构成了一点模糊。
答案 2 :(得分:0)
SELECT
@rank:=@rank+1 as rank,
m.member_id AS member_id,
(SUM(c.vote_value) + SUM(c.best)*10) AS total
FROM comments c,
(SELECT @rank:=0) as init
LEFT JOIN members m ON c.author_id = m.member_id
GROUP BY c.author_id
ORDER BY total DESC
LIMIT {$sql_start}, 20
在解决方案中,即使总数相同,等级也总是在增加。