如何在 MySQL 資料庫僅找到並替換特定字串中的字串?


使用 replace() 函式替換 MySQL 資料庫中的字串。

語法如下所示

UPDATE yourTableName
SET yourColumnName=replace(yourColumnName,'yourExistingValue','yourNewValue')
WHERE <yourCondition>>;

為了理解上述語法,讓我們建立一個表。建立表的查詢如下所示

mysql> create table findAndReplaceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentFirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.49 sec)

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

查詢如下所示

mysql> insert into findAndReplaceDemo(StudentFirstName) values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Bob');
Query OK, 1 row affected (0.10 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Maxwell');
Query OK, 1 row affected (0.17 sec)

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

查詢如下所示

mysql> select *from findAndReplaceDemo;

以下是輸出結果

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Maxwell          |
+----+------------------+
6 rows in set (0.00 sec)

以下是查詢並僅替換 MySQL 資料庫中特定字串的查詢

mysql> update findAndReplaceDemo
   -> set StudentFirstName=replace(StudentFirstName,'Maxwell','Chris')
   -> where StudentFirstName='Maxwell';
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

讓我們再次檢查表記錄,“Maxwell”的值已更改為“Chris”。

查詢如下所示

mysql> select *from findAndReplaceDemo;

以下是更新後的輸出結果

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Chris            |
+----+------------------+
6 rows in set (0.00 sec)

更新於: 30-Jul-2019

2K+ 瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.