MySQL 處理行號

神諭丶發表於2014-08-18
首先建立一個測試表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部落格 ” ,連結:http://blog.itpub.net/29773961/viewspace-1252921/,如需轉載,請註明出處,否則將追究法律責任。

相關文章