gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:30:57 26 4
gpt4 key购买 nike

我在 post_content 列中有 html 内容。

我想搜索 A 并将其替换为 B,但只是 A 第一次出现在记录中,因为它可能出现多次。

下面的查询显然会将 A 的所有实例替换为 B

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

最佳答案

这实际上应该是您在 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));

它比我之前的回答稍微复杂一些 - 您需要找到“A”的第一个实例(使用 INSTR 函数),然后结合使用 LEFT 和 REPLACE 来替换那个实例,而不是使用 SUBSTRING 和 INSTR 来找到您要替换的同一个 'A' 并将其与之前的字符串连接。

请看下面我的测试:

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;

产生:

actual_string                                  new_string
--------------------------------------------- ---------------------------------------------
this is A string with A replace and An Answer this is B string with A replace and An Answer

关于mysql - SQL:搜索/替换,但仅在值第一次出现在记录中时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com