如何使用 MySQL UPDATE 刪除連字元?


要使用 MySQL update 刪除連字元,可以使用 replace() 函式。語法如下 −

update yourTableName
   set yourColumnName=replace(yourColumnName,'-', '' );

為了理解以上語法,我們建立一個表。建立表的查詢如下 −

mysql> create table removeHyphensDemo
   -> (
   -> userId varchar(100)
   -> );
Query OK, 0 rows affected (0.62 sec)

使用 insert 命令插入一些記錄到表中。查詢如下 −

mysql> insert into removeHyphensDemo values('John-123-456');
Query OK, 1 row affected (0.22 sec)
mysql> insert into removeHyphensDemo values('Carol-9999-7777-66555');
Query OK, 1 row affected (0.19 sec)
mysql> insert into removeHyphensDemo values('123456-Bob-8765');
Query OK, 1 row affected (0.14 sec)
mysql> insert into removeHyphensDemo values('1678-9870-Sam');
Query OK, 1 row affected (0.21 sec)

使用 select 語句從表中顯示所有記錄。查詢如下 −

mysql> select *from removeHyphensDemo;

以下是輸出 −

+-----------------------+
| userId                |
+-----------------------+
| John-123-456          |
| Carol-9999-7777-66555 |
| 123456-Bob-8765       |
| 1678-9870-Sam         |
+-----------------------+
4 rows in set (0.00 sec)

以下是刪除連字元的查詢 −

mysql> update removeHyphensDemo
   -> set userId=replace(userId,'-','');
Query OK, 4 rows affected (0.26 sec)
Rows matched: 4 Changed: 4 Warnings: 0

讓我們再次檢查表記錄。查詢如下 −

mysql> select *from removeHyphensDemo;

以下是沒有連字元的輸出 −

+--------------------+
| userId             |
+--------------------+
| John123456         |
| Carol9999777766555 |
| 123456Bob8765      |
| 16789870Sam        |
+--------------------+
4 rows in set (0.00 sec)

更新時間: 2019 年 7 月 30 日

771 次瀏覽

開啟你的 職業生涯

透過完成課程,獲得認證

開始操作
廣告
© . All rights reserved.