仅对MySQL表记录中首次出现的字符执行搜索/替换?

您可以通过CONCAT()withREPLACE()函数的帮助来实现。要查找首次出现的情况,您需要使用INSTR()函数。

语法如下-

UPDATE yourTableName
SET UserPost = CONCAT(REPLACE(LEFT(yourColumnName, INSTR(yourColumnName, 'k')), 'k', 'i'),
SUBSTRING(yourColumnName, INSTR(yourColumnName, 'k') + 1));

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table UserInformation
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(10),
   -> UserPost text
   -> );

现在,您可以使用insert命令在表中插入一些记录。查询如下-

mysql> insert into UserInformation(UserName,UserPost) values('Larry','Thks is a MySQL query');
mysql> insert into UserInformation(UserName,UserPost) values('Mike','Thks is not a java program');
mysql> insert into UserInformation(UserName,UserPost) values('Sam','Thks is a SQL syntax');

使用select语句显示表中的所有记录。查询如下-

mysql> select *from UserInformation;

以下是输出-

+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | Thks is a MySQL query      |
|      2 | Mike     | Thks is not a java program |
|      3 | Sam      | Thks is a SQL syntax       |
+--------+----------+----------------------------+
3 rows in set (0.00 sec)

这是要搜索/替换的查询,但只有第一次在记录中出现一个值。在这里,第一次出现的'k'被替换为'i'-

mysql> update UserInformation
   -> set UserPost=CONCAT(REPLACE(LEFT(UserPost, INSTR(UserPost, 'k')), 'k', 'i'),
   -> SUBSTRING(UserPost, INSTR(UserPost, 'k') + 1));
Rows matched: 3 Changed: 3 Warnings: 0

再次显示表中的所有记录。查询如下-

mysql> select *from UserInformation;

以下是显示用'I'代替的'k'第一次出现的输出-

+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | This is a MySQL query      |
|      2 | Mike     | This is not a java program |
|      3 | Sam      | This is a SQL syntax       |
+--------+----------+----------------------------+
3 rows in set (0.00 sec)