由于业务需求需要获取所有用户的第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