问题
I will ask about SQL replacement function.
I need to your bits of help. In Wordpress DB, I must change a little part. I want to replace first result only in a column. I will explain by giving an example,
My string is = "Hello XXX tomorrow we XXX will meeting in XXX Dubai, Do you want join us XXX ? "
My result must be like this= "Hello MMM tomorrow we XXX will meeting in XXX Dubai, Do you want join us XXX ? "
in this example, we putted MMM to first result of XXX . How i can do it ?
I tried below this code but, it replaced every XXX to MMM;
UPDATE wp_comments SET comment_content = REPLACE ( comment_content, 'XXX', 'MMM' ) WHERE `comment_ID`=334 LIMIT 1
回答1:
In MySQL < 8.0, where regexp_replace()
and the-like are not supported, you can use string functions:
update wp_comments
set comment_content = concat(
substr(comment_content, 1, locate('XXX', comment_content) - 1),
'MMM',
substr(comment_content, locate('XXX', comment_content) + 3)
)
where comment_id = 334 and locate('XXX', comment_content) > 0
Demo on DB Fiddle:
comment_id | comment_content ---------: | :----------------------------------------------------------------------------- 334 | Hello MMM tomorrow we XXX will meeting in XXX Dubai, Do you want join us XXX ?
回答2:
regexp_replace() can do what you want. It takes an optional argument which is the occurrence to replace:
UPDATE wp_comments
SET comment_content = REGEXP_REPLACE( comment_content, 'XXX', 'MMM', 1, 1 )
WHERE comment_ID = 334
LIMIT 1;
来源:https://stackoverflow.com/questions/61159171/how-i-can-replace-only-first-result-in-sql-function