2010-05-25 97 views
1

我有評論表,其中的一切都存儲,我必須彙總一切,並添加BEST ANSWER * 10。 我需要排列整個列表,以及如何顯示指定用戶/ ID的排名。如何獲得基於SUM的排名?

這裏是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 
+1

我不明白 - 查詢看起來很好。也許一些樣本數據和預期產出會有所幫助? – 2010-05-25 20:59:02

+0

Rank,如何顯示排名,以及指定的UID – Kenan 2010-05-25 20:59:46

回答

0

怎麼是這樣的:

SET @rank=0; 
SELECT * FROM (
    SELECT @rank:[email protected]+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 
+0

其實我不能使用SET,它的ExpressionEngine和SQL模塊不允許SET @ rank = 0;一切都必須在一條線上,不要「;」 – Kenan 2010-05-25 21:04:09

+0

在這種情況下,我不知道如何在MySQL中做到這一點。但是你可以從你的極限中獲得等級,對吧?你只需要在程序中而不是在MySQL中計算排名。 – Wolph 2010-05-26 00:28:22

0

你可能想看看windowing functions如果你的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; 

注:圍繞此問題有很多開放性問題,但上述兩種技術是確定排名的一般方法。你需要改變上面的內容以適合你的確切需要,因爲我對member_id的排名構成了一點模糊。

0
SELECT 
    @rank:[email protected]+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 

在該解決方案中,即使總數相同,排名也始終在增加。