MySQL的Replace函数都有哪些用法,你是否都知晓呢?

replace 函数语法-查询操作

replace(String,from_str,to_str)

将String中所有出现的from_str替换为to_str,这里的from_str不支持正则匹配。

数据如下:

mysql> select * from a;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | xiaofei-a |
|  2 | ceshi-b   |
|  3 | ceshi-c   |
+----+-----------+
3 rows in set (0.06 sec)

需求: 把name中所有 - 替换成 #

mysql> select id,replace(name,'-','#') from a;
+----+-----------------------+
| id | replace(name,'-','#') |
+----+-----------------------+
|  1 | xiaofei#a             |
|  2 | ceshi#b               |
|  3 | ceshi#c               |
+----+-----------------------+
3 rows in set (0.07 sec)

replace 函数语法-更新操作

需求: 把name中所有 - 替换成 =

mysql> update a set name = replace(name,'-','=');
Query OK, 3 rows affected (0.03 sec)
Rows matched: 3  Changed: 3  Warnings: 0


mysql> select * from a;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | xiaofei=a |
|  2 | ceshi=b   |
|  3 | ceshi=c   |
+----+-----------+
3 rows in set (0.08 sec)

replace 函数语法-插入操作

如果我们想插入一条新记录,但如果记录已经存在,就先删除原记录,再插入新记录。

插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。

mysql> replace into a (id,name) values (1,'xiaofei666');
Query OK, 2 rows affected (0.03 sec)

mysql> select * from a;
+----+------------+
| id | name       |
+----+------------+
|  1 | xiaofei666 |
|  2 | ceshi=b    |
|  3 | ceshi=c    |
+----+------------+
3 rows in set (0.06 sec)