1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レコードをグルーピングする

Posted at

##概要

グルーピングするカラムに値を入れるとき、1行フェッチして前のレコードと比較で云々とかやりがちだけど、mysqlはリファレンスにも書いてあるこのやり方で、超簡単に採番できる。

##やり方
まず、MyISAMでグルーピングするカラムをAUTO_INCREMENTで作る。その時のPKは複合キーにしてやる。

create table seq_gid
    ( gid_val char(3)
     ,gid     int auto_increment
     ,id      int
     ,primary key(gid_val,gid) )
    engine=myisam;

あとは、以下のようにインサートすればいい。

insert into seq_gid(gid_val,id) values('AAA',1);
insert into seq_gid(gid_val,id) values('AAA',2);
insert into seq_gid(gid_val,id) values('BBB',3);
insert into seq_gid(gid_val,id) values('BBB',4);
insert into seq_gid(gid_val,id) values('BBB',5);
insert into seq_gid(gid_val,id) values('CCC',6);

すると、こうなる。

mysql> select * from seq_gid;
+---------+-----+------+
| gid_val | gid | id   |
+---------+-----+------+
| AAA     |   1 |    1 |
| AAA     |   2 |    2 |
| BBB     |   1 |    3 |
| BBB     |   2 |    4 |
| BBB     |   3 |    5 |
| CCC     |   1 |    6 |
+---------+-----+------+
6 rows in set (0.00 sec)

簡単すぎて、鼻水出る。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?