MySQL行號問題

壹頁書發表於2014-04-21
MySQL技術內幕 SQL程式設計 114頁

方法一,相關子查詢
    需要一個唯一列,並且這個列本身有一定的順序。
  1. create table test(
  2.         name varchar(20) primary key
  3. );

  4. insert into test values('A');
  5. insert into test values('B');
  6. insert into test values('C');
  7. commit;

  8. --子查詢
  9. select name,(select count(*) from test t1 where t2.name>=t1.name) rownum from test t2;


 --中間結果

  1. mysql> select count(*) from test where name<='A';
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 1 |
  6. +----------+
  7. 1 row in set (0.00 sec)

  8. mysql> select count(*) from test where name<='B';
  9. +----------+
  10. | count(*) |
  11. +----------+
  12. | 2 |
  13. +----------+
  14. 1 row in set (0.00 sec)

  15. mysql> select count(*) from test where name<='C';
  16. +----------+
  17. | count(*) |
  18. +----------+
  19. | 3 |
  20. +----------+
  21. 1 row in set (0.00 sec)

如果這個列本身沒有順序,則不能生成rownum。不過考慮到InnoDB是索引組織表,根據主鍵都是符合要求的。
  1. create table test(
  2.         name int
  3. );

  4. insert into test values(200);
  5. insert into test values(150);
  6. insert into test values(250);
  7. commit;

  8. mysql> select name,(select count(*) from test t1 where t2.name>=t1.name) rownum from test t2;
  9. +------+--------+
  10. | name | rownum |
  11. +------+--------+
  12. | 200 | 2 |
  13. | 150 | 1 |
  14. | 250 | 3 |
  15. +------+--------+
  16. 3 rows in set (0.00 sec)

方法二,笛卡爾積        
    需要一個唯一列,並且這個列本身有一定的順序。
  1. mysql> select a.name,count(*) from test a,test b where a.name>=b.name group by a.name;
  2. +------+----------+
  3. | name | count(*) |
  4. +------+----------+
  5. | A | 1 |
  6. | B | 2 |
  7. | C | 3 |
  8. +------+----------+
  9. 3 rows in set (0.01 sec)

  10. --中間結果
  11. mysql> select a.*,b.* from test a,test b where a.name>=b.name ;
  12. +------+------+
  13. | name | name |
  14. +------+------+
  15. | A | A |
  16. | B | A |
  17. | B | B |
  18. | C | A |
  19. | C | B |
  20. | C | C |
  21. +------+------+
  22. 6 rows in set (0.00 sec)

方法三 使用者自定義變數
  1. mysql> set @a=0;
  2. Query OK, 0 rows affected (0.00 sec)

  3. mysql> select name,@a:=@a+1 from test;
  4. +------+----------+
  5. | name | @a:=@a+1 |
  6. +------+----------+
  7. | A | 1 |
  8. | B | 2 |
  9. | C | 3 |
  10. +------+----------+
  11. 3 rows in set (0.00 sec)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1146496/,如需轉載,請註明出處,否則將追究法律責任。

相關文章