如何從 MySQL 中的字串中提取數字部分?


我們首先建立一個表 −

mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.71 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values('John19383');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Carol9999');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('David123456');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

輸出

這將產生以下輸出 −

+-------------+
| StudentId   |
+-------------+
| John19383   |
| Carol9999   |
| David123456 |
+-------------+
3 rows in set (0.00 sec)

以下是從字串中提取數字部分的查詢 −

mysql> SELECT replace(reverse(FORMAT(reverse(StudentId), 0)), ',', '') as OnlyDigit from DemoTable;

輸出

這將產生以下輸出 −

+-----------+
| OnlyDigit |
+-----------+
| 19383     |
| 9999      |
| 123456    |
+-----------+
3 rows in set (0.05 sec)

更新於: 2020-06-30

2K+ 瀏覽

開啟你的職業

完成課程並獲得認證

開始
廣告