LoginSignup
18
10

More than 5 years have passed since last update.

【MySQL】グループ毎に連番を振る

Posted at

用途

日付順で表示していた一覧にソート順変更機能を追加したい時の既存データの変換対応など

抽出方法

id group_id title description created_date
1 1 件名1 本文1 2017-03-24 14:47:16
2 1 件名2 本文2 2017-03-24 14:47:21
3 1 件名3 本文3 2017-03-24 14:47:26
4 2 件名4 本文4 2017-03-24 14:47:30
5 2 件名5 本文5 2017-03-24 14:47:35
6 3 件名6 本文6 2017-03-24 14:47:39

上記のテーブルのgroup_id毎に1からはじまる連番を振りたい。
created_dateの古いものから連番を振っていく。

set @no:=0;
set @groupid:=null;

select
    id,
    group_id,
    title,
    description,
    created_date,
    if(@groupid <> group_id, @no:=1, @no:=@no+1) as no,
    @groupid:=group_id
from articles
order by group_id,created_date;

前の行の値と比較し、違う値に変わっていたら1を代入、group_idが同じ場合は1ずつ追加していく。

id group_id title description created_date no @groupid:=group_id
1 1 件名1 本文1 2017-03-24 14:47:16 1 1
2 1 件名2 本文2 2017-03-24 14:47:21 2 1
3 1 件名3 本文3 2017-03-24 14:47:26 3 1
4 2 件名4 本文4 2017-03-24 14:47:30 1 2
5 2 件名5 本文5 2017-03-24 14:47:35 2 2
6 3 件名6 本文6 2017-03-24 14:47:39 1 3
18
10
1

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
18
10