1

我有存储所有内容的评论表,我必须对所有内容求和并添加最佳答案 * 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
4

3 回答 3

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
于 2010-05-25T21:01:51.777 回答
0

如果您的 MySQL 版本支持窗口函数,您可能需要检查它们...

 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;

NB:这方面有很多悬而未决的问题,但上述两种技术通常是确定排名的简单方法。您需要更改以上内容以满足您的确切需求,因为我对 member_id 排名的构成有点模糊。

于 2010-05-25T21:16:34.190 回答
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

在解决方案中,即使总数相同,排名也总是在增加。

于 2010-05-25T21:36:24.980 回答