Mysql 中根据条件排序获取排名

1       SELECT user_id,left_credit,(@rownum:=@rownum+1) AS rownum
2       FROM credit_user ,(SELECT @rownum:=0) r
3       ORDER BY left_credit DESC

上面示例根据left_credit字段条件进行倒序排序,然后通过rownum获取到排名从1开始

 

      SELECT user_id,left_credit,(@rownum:=@rownum+1) AS rownum
      FROM credit_user 
      ORDER BY left_credit DESC

 去掉 (SELECT @rownum:=0) r 后,rownum就不是每次控制从1开始,而是没执行一次就逐次自增

   select * from (SELECT user_id,left_credit,(@rownum:=@rownum+1) AS rownum
      FROM credit_user ,(SELECT @rownum:=0) r
      ORDER BY left_credit DESC)T having rownum>n

排序后 选择某一行或者某几行,n是行数。

 

posted @ 2019-07-18 14:46  乐在跑途  阅读(3384)  评论(0编辑  收藏  举报