仅在 MySQL 表记录中对字符的第一次出现执行搜索/替换?
你可以借助 CONCAT() 和 REPLACE() 函数实现此操作。找到首次出现时,你需要使用 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 -> ); Query OK, 0 rows affected (2.05 sec)
现在,你可以使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into UserInformation(UserName,UserPost) values('Larry','Thks is a MySQL query'); Query OK, 1 row affected (0.16 sec) mysql> insert into UserInformation(UserName,UserPost) values('Mike','Thks is not a java program'); Query OK, 1 row affected (0.31 sec) mysql> insert into UserInformation(UserName,UserPost) values('Sam','Thks is a SQL syntax'); Query OK, 1 row affected (0.18 sec)
使用 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)); Query OK, 3 rows affected (0.16 sec) Rows matched: 3 Changed: 3 Warnings: 0
再次从表中显示所有记录。查询如下 −
mysql> select *from UserInformation;
以下为显示首次出现的‘k’替换为‘I’的输出 −
+--------+----------+----------------------------+ | 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)
广告