ITPub博客

首页 > 数据库 > MySQL > MySQL 处理行号

MySQL 处理行号

翻译 MySQL 作者:神谕丶 时间:2014-08-18 09:40:53 0 删除 编辑
首先创建一个测试表row_number:

  1. create table row_number(a char(1));

再插入一些测试数据:
  1. insert into row_number select 'X';
  2. insert into row_number select 'X';
  3. insert into row_number select 'X';
  4. insert into row_number select 'Y';
  5. insert into row_number select 'Y';
  6. insert into row_number select 'Z';

如何在select时给出对应的行号呢?


在oracle中有ROWNUM
那么在mysql中如何处理此类问题呢?



首先对a列进行分组,并统计数量及小于该分区数据的数量。

代码实现:

  1. select a,count(*) as count,(select count(*)
  2.                             from row_number as b
  3.                             where b.a < a.a) as smaller
  4. from row_number as a
  5. group by a;

然后和数字辅助表连接,通过辅助表来对上述产生的结果集进行复制,每行复制的记录数由count字段决定。
记录X需要复制3次,记录Y需要复制2次,记录Z需要复制1次。
(数字辅助表在之前的博文中有提到)

代码实现:

  1. select *
  2. from(select a,count(*) as count,(select count(*)
  3.                                 from row_number as b
  4.                                 where b.a < a.a) as smaller
  5.     from row_number as a
  6.     group by a) as c,nums
  7. where nums.a<=count;

(其中a1为数字辅助表nums返回的列名,原辅助表中列名为a,但此处有重合,故nums的a列被mysql自动命名为a1)


我们发现,smaller和a1之和便是我们要的行号
只需要做一次加和便可:
代码实现:

  1. select nums.a+smaller as rownum,c.a
  2. from(select a,count(*) as count,(select count(*)
  3.                                 from row_number as b
  4.                                 where b.a < a.a) as smaller
  5.     from row_number as a
  6.     group by a) as c,nums
  7. where nums.a<=count;




来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1252921/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: MySQL range问题
下一篇: MySQL 除法问题
请登录后发表评论 登录
全部评论
微信公众号:神谕的暗影长廊

注册时间:2014-07-28

  • 博文量
    161
  • 访问量
    1195299