【发布时间】:2017-12-07 07:20:59
【问题描述】:
我正在写一个sql来获取一个数字列表的媒介(假设列表的长度是奇数)
set @r=0;
select S.num
from
(select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1
order by num) S
where rowIndex = ceil(@r/2)
这个查询有效,但是,我对我的子查询感到困惑。我的问题如下:如果我只是输入
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1
我将有 2 列,第一列是原始顺序中的原始数字列表,例如 10,1,3,11,5,4,19...,第二列是行索引,1,2 ,3,4,.... 请注意,我想要的是首先按升序对原始列表进行排序,然后为每一行指定其行索引。
我一开始以为
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1
order by num
将生成一个表,其中第一列是我的原始列表的排序版本,但第二列是索引集 [1,2,3,...] 的重新排列。因为我认为查询的顺序是:首先按照select num, case when num is not NULL then (@r:=@r+1) end as rowIndex from T1的建议创建一个表,然后按num列对该表进行排序,因此,当num列排序时,rowIndex列应该没有不再是 [1,2,3,...]。
但实际上,它似乎首先对num 列进行排序,然后添加行索引。换句话说,我发现无论我是否添加order by num,第二列总是一个不错的行索引[1,2,3,4,...]。为什么?
【问题讨论】:
-
你能添加一个表格数据示例吗,因为现在很难理解你在说什么
-
@NorbertvanNobelen 抱歉,我正要这样做,@Used_By_Already 在下面的答案中做了一个表格。但是我仍然对Mysql中的这个
order by子句感到困惑