6
4

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 3 years have passed since last update.

【mysql】UPDATEで連番を振り直す

Last updated at Posted at 2020-01-24

はじめに

  • テストとかしてカラムごにゃった時に番号がずれてしまったりしたので、連番をきれいに振り直したいと思ったしだい。
  • 忘れがちなので、書いておくことにした

mysql のバージョン

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.28    |
+-----------+

やってみる

  • 例えば、この↓ select文のnoが1から始まって欲しいのに2から始まってる。
mysql> select id, no from tests; 
+----+----+
| id | no |
+----+----+
|  1 |  2 |
|  2 |  3 |
|  3 |  4 |
|  4 |  5 |
+----+----+
4 rows in set (0.00 sec)
  • 振り直す!!
mysql> set @cnt_i:=0; update tests set no = (@cnt_i := @cnt_i + 1 );

Query OK, 0 rows affected (0.00 sec)
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4  Changed: 4  Warnings: 0
  • 確認してみる。無事に no が 1 からの連番になっている。やったー
mysql> select id, no from tests; 
+----+----+
| id | no |
+----+----+
|  1 |  1 |
|  2 |  2 |
|  3 |  3 |
|  4 |  4 |
+----+----+
4 rows in set (0.01 sec)
6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?