刪除 MySQL 列中用括號括起來的尾部數字


為此,請結合使用 trim() 與 substring()。我們先建立一個表 −

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

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

mysql> insert into DemoTable values('1stJohn');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('1stJohn (7)');
Query OK, 1 row affected (0.65 sec)
mysql> insert into DemoTable values('2ndSam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('2ndSam (4)');
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

將會產生以下輸出 −

+-------------+
| Name        |
+-------------+
| 1stJohn     |
| 1stJohn (7) |
| 2ndSam      |
| 2ndSam (4)  |
+-------------+
4 rows in set (0.00 sec)

以下是查詢以從 MySQL 列中刪除用括號括起來的尾部數字 −

mysql> select trim(substring(Name, 1, (CHAR_LENGTH(Name) - LOCATE('(', REVERSE(Name))))) AS RemovingTrailingNumbers from DemoTable;

將會產生以下輸出 −

+-------------------------+
| RemovingTrailingNumbers |
+-------------------------+
| 1stJohn                 |
| 1stJohn                 |
| 2ndSam                  |
| 2ndSam                  |
+-------------------------+
4 rows in set (0.00 sec)

更新時間:26-9 月 -2019

140 次瀏覽

開啟您的 職業

完成課程認證

入門
廣告
© . All rights reserved.