+-

我在post_content列中有html内容.
我想搜索并用A替换A,但只有A第一次出现在记录中,因为它可能出现不止一次.
以下查询显然会替换A与B的所有实例
更新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’你正在用前一个字符串替换和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;
生产:
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:搜索/替换但只是第一次出现在记录中的值 - 乐贴网