2016-07-26 58 views
0

我不明白爲什麼排序不能正確使用「ORDER BY average,votes DESC」,因爲我需要最高的平均值並且票數是從頂部到底部的,但DESC沒有解決什麼問題。我在var_dump http://pastie.org/private/b05smuh0fvw72wwp2w1zq最高entrie的結果是在底部,但我需要從頂部開始並進入底部。使用DESC的SQL查詢無法正常工作

SELECT c.*, r.votes, c.total_comments, 
     ROUND(sumrate/votes) AS average 
FROM catalog c LEFT JOIN 
    (SELECT r.object_id, COUNT(*) as votes, SUM(r.rate) as sumrate 
     FROM ratings r 
     GROUP BY r.object_id 
    ) r 
    ON r.object_id = c.catalog_id LEFT JOIN 
    (SELECT c.catalog_id, COUNT(*) as total_comments 
     FROM comments c 
     GROUP BY c.catalog_id 
    ) c 
    ON c.catalog_id = c.catalog_id 
GROUP BY c.catalog_id 
ORDER BY average, votes DESC; 
+1

請注意,GROUP BY是無效的,並且在更新的MySQL版本中不允許。 (如果指定了GROUP BY子句,則SELECT列表中的每個列引用都必須標識分組列或作爲set函數的參數。) – jarlh

+0

你是什麼意思?分組中的簡短表別名是什麼?你能舉個例子嗎? – SkySonny

回答

5

因爲您可以爲每列定義訂單,而不僅限於總共order by。默認值是ASC

您的訂單

ORDER BY average, votes DESC 

自動轉成

ORDER BY average ASC, votes DESC 

但你正在尋找

ORDER BY average DESC, votes DESC 
3

你需要指定DESC兩個列。否則,默認情況下它是ASC

SELECT c.*, r.votes, c.total_comments, 
     ROUND(sumrate/votes) AS average 
FROM catalog c LEFT JOIN 
    (SELECT r.object_id, COUNT(*) as votes, SUM(r.rate) as sumrate 
     FROM ratings r 
     GROUP BY r.object_id 
    ) r 
    ON r.object_id = c.catalog_id LEFT JOIN 
    (SELECT c.catalog_id, COUNT(*) as total_comments 
     FROM comments c 
     GROUP BY c.catalog_id 
    ) c 
    ON c.catalog_id = c.catalog_id 
GROUP BY c.catalog_id 
ORDER BY average DESC, votes DESC;