MySQL SQLの結果に連番を振る

 

 

 

(SELECT @num := -1) as dmy で連番用の仮想テーブルを記述、
@num := @num + 1 AS ID のような列を記述します。

mysql> SELECT
    ->   @num := @num + 1 AS ID,
    ->   CD,
    ->   K_NAME, H_NAME
    -> FROM
    ->   (SELECT @num := -1) as dmy,
    ->   m_todou
    -> LIMIT 0, 5;
+------+----+-----------+--------------------+
| ID   | CD | K_NAME    | H_NAME             |
+------+----+-----------+--------------------+
|    0 |  1 | 北海道    | ほっかいどう       |
|    1 |  2 | 青森県    | あおもりけん       |
|    2 |  3 | 岩手県    | いわてけん         |
|    3 |  4 | 宮城県    | みやぎけん         |
|    4 |  5 | 秋田県    | あきたけん         |
+------+----+-----------+--------------------+
5 rows in set (0.00 sec)

mysql> show create table m_todou;
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                    |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| m_todou | CREATE TABLE `m_todou` (
  `CD` tinyint(4) NOT NULL,
  `K_NAME` varchar(8) NOT NULL,
  `H_NAME` varchar(12) NOT NULL,
  PRIMARY KEY (`CD`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='都道府県マスタ'        |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> 

 

 

コメントを残す