mysql实现分组排序,获取第N条数据

来源:互联网 发布:数据分析 知乎 编辑:程序博客网 时间:2024/05/29 03:23

由于业务需求需要获取所有用户的第N条记录目前想到两种方式:

第一种方式用group_concat() 列转行 然后substring_index() 截取的方式性能扩展不太好:

select t.userId,substring_index(group_concat( t.mount ORDER BY t.createtime ),',',2)  amount,substring_index(group_concat( t.other ORDER BY t.createtime ),',',2)  other from   t  group by t.userId


第二种使用rownum性能较好比较灵活

</pre><pre name="code" class="sql">SELECTid,userId,content,rankFROM(SELECTb.id,b.userId,b.content ,@rownum :=@rownum + 1,IF (@pdept = b.userId ,@rank :=@rank + 1 ,@rank := 1) AS rank,@pdept := b.userIdFROM(SELECTid,userId,contentFROMmyTableWHEREpnrStatus = 1ORDER BYuserId,id) b,(SELECT@rownum := 0,@pdept := NULL ,@rank := 0) c) result




0 0
原创粉丝点击