我有一个简单的数据表,我想从查询中选择大约40个百分位数的行。

我现在可以通过第一次查询查找行数,然后运行另一个查询,然后选择第n行:

select count(*) as `total` from mydata;

可能返回93、93*0.4 = 37

select * from mydata order by `field` asc limit 37,1;

我可以将这两个查询组合到一个查询中吗?

有帮助吗?

解决方案

这将为您提供大约40个百分点的时间,它返回了40%的行小于它的行。它会排在第40个百分位数的距离之内,因为没有排可能完全落在第40个百分位上。

SELECT m1.field, m1.otherfield, count(m2.field) 
  FROM mydata m1 INNER JOIN mydata m2 ON m2.field<m1.field
GROUP BY 
   m1.field,m1.otherfield
ORDER BY 
   ABS(0.4-(count(m2.field)/(select count(*) from mydata)))
LIMIT 1

其他提示

作为徒劳的练习(如果桌子是myisam(或者您可以与InnoDB的近似),您的当前示意图可能会更快,更喜欢):

SET @row =0;
SELECT x.*
FROM information_schema.tables
JOIN (
  SELECT @row := @row+1 as 'row',mydata.*
  FROM mydata
  ORDER BY field ASC
) x
ON x.row = round(information_schema.tables.table_rows * 0.4)
WHERE information_schema.tables.table_schema = database()
AND information_schema.tables.table_name = 'mydata';

还有 解决方案,使用group_concat制作的怪物字符串。我不得不像输出一样提高最大值才能使其正常工作:

SET SESSION group_concat_max_len = 1000000;

MySQL向导:随时评论方法的相对性能。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top