Mysql:使用限制与Con

时间:2016-04-08 08:20:10

标签: mysql sql-order-by limit

我已经得到了这个查询,它给出了特定国家/地区的所有评分:

SELECT DISTINCT Country, GROUP_CONCAT(rating ORDER BY rating DESC ) AS Ranking
FROM final
group by Country
ORDER BY Country;

表格是这样的:

"Country"   "Rating"    "Title" 
" zimbabwe" "0" "Biology Study Guide" 
" zimbabwe" "0" "Impact: A Guide to Business Communication (Esl English 2nd Language Series)" 
" zimbabwe" "0" "Wayside School Gets a Little Stranger (Wayside School)" 
" ysa"  "5" "Side effects" 
" ysa"  "9" "The Last Precinct" 
" ysa"  "0" "The Horse Whisperer" 
" x"    "0" "The Evi 
" yugoslavia"   "0" "Wild Animus" 
" yugoslavia"   "8" "Complete Works of William Shakespeare (Wordsworth Royals Series)" 
" yugoslavia"   "3" "Wild Animus"

我遇到了两个问题。我试图将评级限制在每个国家10。我在LIMIT 10之后添加了DESC,我收到了语法错误。

第二个问题是,在DESC顺序中,10低于9,因为它从1开始。我该如何处理?

1 个答案:

答案 0 :(得分:2)

为了限制GROUP_CONCAT(),您可以使用SUBSTRING_INDEX()来削减所需的元素。要将字符串作为数字排序,您可以使用CAST()。因此,您的查询应如下所示:

SELECT DISTINCT
    Country,
    SUBSTRING_INDEX(
        GROUP_CONCAT(rating ORDER BY CAST(rating AS UNSIGNED) DESC), ',', 10
    ) AS Ranking
FROM
    final
GROUP BY
    Country
ORDER BY
    Country;