在选择MySQL中返回前N%个记录

时间:2018-06-20 00:00:39

标签: mysql sql

我需要返回select中所有记录的33%

select id , amount, 'low'
from table 1 
where amount > 1
order by 2;

所以我需要先返回此记录的33%

1 个答案:

答案 0 :(得分:2)

我认为您需要枚举行,除了最新版本的MySQL外,所有行都需要变量:

select t.*
from (select t.*, (@rn := @rn + 1) as rn
      from (select id , amount, 'low' as col
            from table 1 
            where amount > 1
            order by 2
           ) t cross join
           (select @rn := 0) params
     ) t
where rn <= 0.33 * @rn;  -- @rn is now set to the total number of rows