select 10 rows per day with order

前端 未结 9 540
感情败类
感情败类 2021-02-06 16:08

i have a db with records with date (timestamp) i need to select 10 records for each day (there are many more per day) and order them by few columns...

how should that qu

9条回答
  •  太阳男子
    2021-02-06 16:48

    After looking at (the ever excellent) xaprb blog from Baron Schwarz, http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/ I wonder if the use of user-defined variables could work here.

    select hiredate, ename, sal
    from ( select hiredate, ename, sal,
           @num := if(@hiredate = hiredate, @num + 1, 1) as row_number,
           @hiredate := hiredate as dummy
         from emp_temp
    ) as x
    where row_number < 3
    order by hiredate, ename, sal
    

    I've only tried the above for small sets of data, but it seems to work in bringing back just two records per hiredate. So far as I can tell from limited testing it should scale up for greater data sets. ( there may be performance issues in large data sets as Mysql is creating a temporary table)

提交回复
热议问题