在 MySQL 列中添加前导零?

mysqlmysqli database更新于 2025/12/15 14:36:17

要添加前导零,您可以使用 LPAD()。让我们首先创建一个表 −

mysql> create table DemoTable
(
   Code varchar(100)
);
Query OK, 0 rows affected (0.87 sec)

使用 insert 插入命令在表中插入一些记录 −

mysql> insert into DemoTable values('JS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('CB');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('DM');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('CT');
Query OK, 1 row affected (0.07 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+------+
| Code |
+------+
|   JS |
|   CB |
|   DM |
|   CT |
+------+
4 rows in set (0.00 sec)

现在,让我们在 MySQL 中添加前导零 −

mysql> update DemoTable set Code=LPAD(Code, 8, '0');
Query OK, 4 rows affected (0.10 sec)
Rows matched: 4 Changed: 4 Warnings: 0

让我们再次检查表记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----------+
| Code     |
+----------+
| 000000JS |
| 000000CB |
| 000000DM |
| 000000CT |
+----------+
4 rows in set (0.00 sec)


相关文章


有用资源