如何在 MySQL 中在字首填充“0”到郵編?


若要在郵編字首用 0 填充,請在 MySQL 中使用 LPAD() 函式。語法如下 −

SELECT LPAD(yourColumnName, columnWidth+1, '0') as anyVariableName from yourTableName;

為了理解關於使用 LPAD() 在郵編字首中填充 0 的以上概念,讓我們建立一個表。表的其中一列是郵編。以下是建立表的查詢。

mysql> create table ZipCodePadWithZeroDemo
   −> (
   −> Name varchar(200),
   −> YourZipCode int(6)
   −> );
Query OK, 0 rows affected (0.44 sec)

在表中插入一些記錄。插入記錄的查詢如下 −

mysql> insert into ZipCodePadWithZeroDemo values('John',23455);
Query OK, 1 row affected (0.13 sec)

mysql> insert into ZipCodePadWithZeroDemo values('Carol',46523);
Query OK, 1 row affected (0.62 sec)

mysql> insert into ZipCodePadWithZeroDemo values('Johnson',12345);
Query OK, 1 row affected (0.11 sec)

mysql> insert into ZipCodePadWithZeroDemo values('David',34567);
Query OK, 1 row affected (0.18 sec)

從表中顯示所有記錄。查詢如下 −

mysql> select *from ZipCodePadWithZeroDemo;

以下是輸出 −

+---------+-------------+
| Name    | YourZipCode |
+---------+-------------+
| John    | 23455       |
| Carol   | 46523       |
| Johnson | 12345       |
| David   | 34567       |
+---------+-------------+
4 rows in set (0.00 sec)

實現我們在開頭討論用於在郵編字首填充值 0 的語法。查詢如下 −

mysql> SELECT LPAD(YourZipCode, 6, '0') as UPDATEDZIPCODE from ZipCodePadWithZeroDemo;

我們還將在此獲取名稱 −

mysql> SELECT Name,LPAD(YourZipCode, 6, '0') as UPDATEDZIPCODE from ZipCodePadWithZeroDemo;

以下輸出顯示姓名以及郵編 −

+---------+----------------+
| Name    | UPDATEDZIPCODE |
+---------+----------------+
| John    | 023455         |
| Carol   | 046523         |
| Johnson | 012345         |
| David   | 034567         |
+---------+----------------+
4 rows in set (0.00 sec)

更新時間: 2019 年 7 月 30 日

475 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.