您的位置:首页 > 数据库 > MySQL

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

2016-08-25 10:52 537 查看
由于业务需求需要获取所有用户的第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">SELECT
id,
userId,
content,
rank
FROM
(
SELECT
b.id,
b.userId,
b.content ,@rownum :=@rownum + 1,

IF (
@pdept = b.userId ,@rank :=@rank + 1 ,@rank := 1
) AS rank,
@pdept := b.userId
FROM
(
SELECT
id,
userId,
content
FROM
myTable
WHERE
pnrStatus = 1
ORDER BY
userId,
id
) b,
(
SELECT
@rownum := 0,
@pdept := NULL ,@rank := 0
) c
) result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐