找出用户的最后两行

时间:2013-06-26 03:41:51

标签: mysql

我有这个表,每个用户在表中可以有多行,所以我想找出每个用户的前两行。

我看到了这个链接并尝试了解决方案

SQL - Give me 3 hits for each type only

SELECT user_fk, order_number, @num := IF( @group = user_fk, @num +1, 1 ) AS row_number, @group := user_fk AS dummy
FROM summary
ORDER BY  `user_fk` ASC

我使用上面的查询来查看row_number是否递增,但它没有。知道为什么吗?

2 个答案:

答案 0 :(得分:0)

它正在运作

将其括在内联视图中

sqlfiddle demo

答案 1 :(得分:0)

SELECT user_fk, order_number from 
(SELECT user_fk, order_number, @num := IF( @group = user_fk, @num +1, 1 ) AS row_number, @group := user_fk AS dummy
FROM summary
ORDER BY  `user_fk` ASC) as x 
where row_number<=2

我认为你错过了部分查询。