MySQLでidentity column
以前に書いたidentity columnに関する記事(identity column - テーブルの各行にシーケンス番号を割り当てる - HHeLiBeXの日記 正道編)のMySQL版。
AUTO_INCREMENTというのを列定義に指定すればいいらしい。
CREATE TABLE hoge( seq_num INTEGER AUTO_INCREMENT , msg VARCHAR(32) NOT NULL , primary key(seq_num) )
ただ、いろいろと制約や注意点があるらしい。
- http://dev.mysql.com/doc/refman/5.1/ja/innodb-restrictions.html
- 中ほどにAUTO_INCREMENTに関する説明がある。
- http://dev.mysql.com/doc/refman/5.1/ja/innodb-auto-increment-column.html
- 今感じていること MySQLでauto_incrementを使う時には要注意
自分の環境では、InnoDBを使用しているのだが、主キーをわざわざ指定したのもこれらの制約のひとつによるもの。
実行結果はこんな感じ。
SELECT seq_num, msg from hoge order by msg seq_num msg ----------- -------------------------------- 1 01: first message 2 02: second message 3 03: third message 4 04: fourth message 5 05: fifth message 6 06: sixth message 7 07: seventh message 8 08: eighth message
実際に実行したクエリを保存したファイルは次のとおり。