SQL:搜索/替换,但仅在记录中第一次出现值

ste*_*mie 10 mysql sql replace sql-update

我在post_content列中有html内容.

我想搜索并用A替换A,但只有A第一次出现在记录中,因为它可能出现不止一次.

以下查询显然会替换A与B的所有实例

UPDATE wp_posts SET post_content = REPLACE (post_content, 'A', 'B');

Gre*_*eda 14

这实际上应该是你想要的MySQL:

UPDATE wp_post
SET post_content = CONCAT(REPLACE(LEFT(post_content, INSTR(post_content, 'A')), 'A', 'B'), SUBSTRING(post_content, INSTR(post_content, 'A') + 1));
Run Code Online (Sandbox Code Playgroud)

它比我之前的答案稍微复杂一点 - 你需要找到'A'的第一个实例(使用INSTR函数),然后使用LEFT结合REPLACE来替换那个实例,而不是使用SUBSTRING和INSTR来找到它'A'你正在用前一个字符串替换和CONCAT它.

请参阅下面的测试:

SET @string = 'this is A string with A replace and An Answer';
SELECT @string as actual_string
, CONCAT(REPLACE(LEFT(@string, INSTR(@string, 'A')), 'A', 'B'), SUBSTRING(@string, INSTR(@string, 'A') + 1)) as new_string;
Run Code Online (Sandbox Code Playgroud)

生产:

actual_string                                  new_string
---------------------------------------------  ---------------------------------------------
this is A string with A replace and An Answer  this is B string with A replace and An Answer
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不适用于长于一个字符串的字符串:( (5认同)

And*_*y M 10

或者,您可以使用LOCATE(),INSERT()CHAR_LENGTH()函数,如下所示:

INSERT(originalvalue, LOCATE('A', originalvalue), CHAR_LENGTH('A'), 'B')
Run Code Online (Sandbox Code Playgroud)

完整查询:

UPDATE wp_posts
SET post_content = INSERT(originalvalue, LOCATE('A', originalvalue), CHAR_LENGTH('A'), 'B');
Run Code Online (Sandbox Code Playgroud)