我正在尝试从MySQL表用户中获取前50%的记录。我知道我们可以使用极限或顶部来查找它们,但是记录的总数并不是固定的,所以硬编码限制或顶部的实际数字不会给我前50%的记录。我怎样才能做到这一点?
发布于 2020-05-09 13:24:17
如果您运行的是MySQL 8.0,您可以为此使用窗口函数:ntile()完全满足您的要求。假设您的订购列是id
select *
from (select t.*, ntile(2) over(order by id) nt from mytable) t
where nt = 1在早期版本中,有一个选项是用户变量和聚合查询的联接:
select *
from (
select t.*, @rn := @rn + 1 rn
fom (select * from mytable order by id) t
cross join (select @rn := 0) x
cross join (select count(*) cnt from mytable) c
) t
where rn <= cnt / 2发布于 2020-05-09 13:06:09
Mysql直接不支持这一点。您可以尝试使用两个查询或使用子查询。
就像这样。
SET @count =(从表中选择COUNT(*)/2 );
设置@sql =CONCAT(“选择*从表限制”,@count);
https://stackoverflow.com/questions/61696963
复制相似问题