LoginSignup
0
0

More than 5 years have passed since last update.

varchar の数値を sort して出力

Posted at

以下 code テーブルが varchar の場合、
sortしても順番通りにならない。

mysql> select code from books
 order by code asc;
+---------+
| code    |
+---------+
| 1       |
| 10      |
| 100     |
| 1000    |
| 10000   |
| 100000  |
| 1000001 |
| 1000002 |
| 100001  |
| 100002  |
+---------+
  • cast を使う。 (mysql 4.0.2以降で対応)
mysql> select code from books
 order by cast(code as signed);
+---------+
| code    |
+---------+
| 1       |
| 10      |
| 100     |
| 1000    |
| 10000   |
| 100000  |
| 100001  |
| 100002  |
| 1000001 |
| 1000002 |
+---------+
0
0
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
0
0