如何在 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)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP