19
19

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.

MySQLで桁が足りない分を0で埋める

Posted at

やり方

lpadという関数を使えばOK。

LPAD(str,len,padstr)

試してみる


### テーブルを作る。
mysql> create table demo(id serial primary key, n integer not null);
Query OK, 0 rows affected (0.02 sec)


### とりあえず3件データを挿入。
mysql> insert into demo(n) values(1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into demo(n) values(2);
Query OK, 1 row affected (0.00 sec)

mysql> insert into demo(n) values(300);
Query OK, 1 row affected (0.00 sec)


### 3桁 0埋め
mysql> select lpad(n, 3, '0') from demo;
+-----------------+
| lpad(n, 3, '0') |
+-----------------+
| 001             |
| 002             |
| 300             |
+-----------------+
3 rows in set (0.00 sec)


### 3桁 'A'埋め
mysql> SELECT lpad(n, 3, 'A') from demo;
+-----------------+
| lpad(n, 3, 'A') |
+-----------------+
| AA1             |
| AA2             |
| 300             |
+-----------------+
3 rows in set (0.00 sec)

確かになりました。

注意点

文字列が指定した桁より長かったらどうなるのか、、、

ちゃんとこう書いてありました。

Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.

mysql> SELECT LPAD('hi',4,'??');
        -> '??hi'
mysql> SELECT LPAD('hi',1,'??');
        -> 'h'

やってみましょう。

mysql> select lpad(n, 2, 0) from demo;
+---------------+
| lpad(n, 2, 0) |
+---------------+
| 01            |
| 02            |
| 30            |
+---------------+
3 rows in set (0.00 sec)

ほんとだ。

参考

19
19
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
19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?