MySQL 數字字串格式化,在用數字填充字串後用斜槓填充字串的左側


我們先建立一個表 -

mysql> create table DemoTable1369
    -> (
    -> BatchId varchar(20)
    -> );
Query OK, 0 rows affected (0.46 sec)

使用 insert 命令插入一些記錄到表中。我們在此插入了用斜槓分隔的數字 -

mysql> insert into DemoTable1369 values('19/5');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1369 values('19/78');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1369 values('19/567');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1369 values('19/1234');
Query OK, 1 row affected (0.11 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select * from DemoTable1369;

這樣將產生以下輸出 -

+---------+
| BatchId |
+---------+
| 19/5    |
| 19/78   |
| 19/567  |
| 19/1234 |
+---------+
4 row>

以下是數字字串格式化的查詢。我們已在斜槓後設置零來填充欄位。總欄位寬度由此處數字“1234”的最高欄位值確定,即 4 -

mysql> select
    -> concat(left(BatchId,3), lpad(substring(BatchId, 4), 4, '0'))
    -> from DemoTable1369;

這樣將產生以下輸出 -

+--------------------------------------------------------------+
| concat(left(BatchId,3), lpad(substring(BatchId, 4), 4, '0')) |
+--------------------------------------------------------------+
| 19/0005                                                      |
| 19/0078                                                      |
| 19/0567                                                      |
| 19/1234                                                      |
+--------------------------------------------------------------+
4 rows in set (0.00 sec)

更新於: 2019-11-08

220 檢視次數

開啟您的 職業 生涯

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.