首先创建一个测试表row_number:
-
create table row_number(a char(1));
再插入一些测试数据:
-
insert into row_number select 'X';
-
insert into row_number select 'X';
-
insert into row_number select 'X';
-
insert into row_number select 'Y';
-
insert into row_number select 'Y';
-
insert into row_number select 'Z';
如何在select时给出对应的行号呢?
在oracle中有ROWNUM
那么在mysql中如何处理此类问题呢?
首先对a列进行分组,并统计数量及小于该分区数据的数量。
代码实现:
-
select a,count(*) as count,(select count(*)
-
from row_number as b
-
where b.a < a.a) as smaller
-
from row_number as a
-
group by a;
然后和数字辅助表连接,通过辅助表来对上述产生的结果集进行复制,每行复制的记录数由count字段决定。
记录X需要复制3次,记录Y需要复制2次,记录Z需要复制1次。
(数字辅助表在之前的博文中有提到)
代码实现:
-
select *
-
from(select a,count(*) as count,(select count(*)
-
from row_number as b
-
where b.a < a.a) as smaller
-
from row_number as a
-
group by a) as c,nums
-
where nums.a<=count;
(其中a1为数字辅助表nums返回的列名,原辅助表中列名为a,但此处有重合,故nums的a列被mysql自动命名为a1)
我们发现,smaller和a1之和便是我们要的行号
只需要做一次加和便可:
代码实现:
-
select nums.a+smaller as rownum,c.a
-
from(select a,count(*) as count,(select count(*)
-
from row_number as b
-
where b.a < a.a) as smaller
-
from row_number as a
-
group by a) as c,nums
-
where nums.a<=count;
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1252921/
,如需转载,请注明出处,否则将追究法律责任。