mysql中实现排名的方法:使用demo函数,语法为【SELECT banji,avg(score) as AvgS FROM table_test GROUP BY banji ORDER BY AvgS DESC】。
mysql中实现排名的方法:
可用Demo实现
注意里面的A,属于嵌套查询,所以排名会正确。FROM
(
SELECT A.*,@rank:=@rank+1 as pm
FROM
(
SELECT banji,avg(score) as AvgS FROM table_test GROUP BY banji ORDER BY AvgS DESC
) A ,(SELECT @rank:=0) B
) M
ORDER BY M.banji
如果里面没有子查询,使用下面的SQL,那么排序会出错。出错的取决于GROUP BY 是否有多于一条的分组。SELECT banji,avg(score) as AvgS ,@rank:=@rank+1 as pm
FROM table_test A,(SELECT @rank:=0) B
GROUP BY banji
ORDER BY AvgS DESC
原因:@rank排名发生在GROUP BY 之前。GROUP BY 是对排名后的结果进行分组。如果想对分组后的结果进行排名,请使用子查询。更多相关免费学习推荐:mysql教程(视频)