mysql从每个组中获取最后10条记录

时间:2017-11-07 03:24:22

标签: mysql sql

我有一个名为ware_stock_transaction的mysql表,它有order_noorder_typecreated_dateitem_no

我想从每个项目中获取最后10条记录,如下所示:

item A (10 records)
item B (10 records)
item C (10 records)

1 个答案:

答案 0 :(得分:4)

在MySQL中,您可以使用变量:

select wst.*
from (select wst.*,
             (@rn := if(@i = item_no, @rn + 1,
                        if(@i := item_no, 1, 1)
                       )
             ) as rn
      from ware_stock_transaction wst cross join
           (select @rn := 0, @i := '') params
      order by item_no, created_date desc
     ) wst
where rn <= 10;