以下演示查詢用戶回答數量從高到低降序查詢,並且輸出當前用戶回答排名序號:
關鍵查詢ROUND(@rownum := @rownum + 1) rownum ,(SELECT @rownum := 0) r
select t.rownum rownum,t.count count from (
select a.user_id,a.count,ROUND(@rownum := @rownum + 1) rownum from (
select user_id,count(1) count from ask_answers
where opt_type =1
<if test="null!=startTime and ''!=startTime">
<![CDATA[ and created_at >= #{startTime,jdbcType=VARCHAR} ]]>
</if>
<if test="null!=endTime and ''!=endTime">
<![CDATA[ and created_at <= #{endTime,jdbcType=VARCHAR} ]]>
</if>
GROUP by user_id
order by count(1) DESC,user_id asc
) a,(SELECT @rownum := 0) r
) t where t.user_id = #{userId,jdbcType=INTEGER}