这是计算 table in mysql 中值的中位数的代码,我需要一些专家来解释命令执行的顺序

This is a code to calculate the median of values in a table in mysql , I need some expert to explain the sequence in which the commands are executing

 set @ct :=(select count(*) from medi);
 set @ro :=0;
 select  avg(num) as median from (select * from medi order by num)  
 where (select @ro:= @ro+1)      
 between @ct/2.0 AND @ct/2.0+1;

table
中的值 +------+
|数 |
+------+
| 2 |
| 55 |
| 63 |
| 85 |
| 32 |
| 15 |
| 3 |
| 36 |
| 69 |
+------+
需要帮助来理解执行顺序和 @ro 在 where 子句中的作用

首先,这个查询产生了错误的结果。它产生了 32 个中位数,这是不正确的。中位数应该是 36

The median is the value separating the higher half of a data sample, a population, or a probability distribution, from the lower half. In simple terms, it may be thought of as the "middle" value of a data set. For example, in the data set {1, 3, 3, 5, 9, 11, 13}, the median is 5, the fourth number in the sample. The median is a commonly used measure of the properties of a data set in statistics and probability theory.

参考:https://en.wikipedia.org/wiki/Median

SQL 的这个位的问题在于它没有对确定中位数所需的值进行排序。

这个 Whosebug 问答:Simple way to calculate median with MySQL 有很多不同的方法来计算中位数并给出解释。

如果你真的想知道上面的查询是做什么的
第一步:计算table
中的行数 Step2:创建一个变量并将其赋值为零
第 3 步:使用变量作为每行递增 1 的数字来查找 table 的中间标记。取中间标记旁边的数字的平均值。

现在你会明白为什么它是错误的,它没有对 table 的内容强加任何顺序。