在MySQL中,如何在邮政编码前面加上“ 0”?

要使用0填充邮政编码,请使用LPAD()MySQL中的function。语法如下-

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

要了解上述LPAD()将前垫邮政编码添加0的概念,让我们创建一个表。该表的列之一是邮政编码。以下是创建表的查询。

mysql> create table ZipCodePadWithZeroDemo
   −> (
   −> Name varchar(200),
   −> YourZipCode int(6)
   −> );

在表中插入一些记录。插入记录的查询如下-

mysql> insert into ZipCodePadWithZeroDemo values('John',23455);

mysql> insert into ZipCodePadWithZeroDemo values('Carol',46523);

mysql> insert into ZipCodePadWithZeroDemo values('Johnson',12345);

mysql> insert into ZipCodePadWithZeroDemo values('David',34567);

显示表中的所有记录。查询如下-

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)