Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

やり方

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)

ほんとだ。

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away