SQL: search/replace but only the first time a value appears in record

后端 未结 9 820
执念已碎
执念已碎 2020-12-11 02:11

I have html content in the post_content column.

I want to search and replace A with B but only the first time A appears in the record as it may appear more than onc

9条回答
  •  臣服心动
    2020-12-11 02:55

    With reference to https://dba.stackexchange.com/a/43919/200937 here is another solution:

    UPDATE wp_posts 
    SET post_content = CONCAT( LEFT(post_content , INSTR(post_content , 'A') -1),
                               'B',
                               SUBSTRING(post_content, INSTR(post_content , 'A') +1))
    WHERE INSTR(post_content , 'A') > 0;
    

    If you have another string, e.g. testing then you need to change the +1 above to the according string length. We can use LENGTH() for this purpose. By the way, leave the -1 untouched.

    Example: Replace "testing" with "whatever":

    UPDATE wp_posts 
    SET post_content = CONCAT( LEFT(post_content , INSTR(post_content , 'testing') -1),
                               'whatever',
                               SUBSTRING(post_content, INSTR(post_content , 'testing') + LENGTH("testing"))
    WHERE INSTR(post_content , 'testing') > 0;
    


    By the way, helpful to see how many rows will be effected:

    SELECT COUNT(*)
    FROM post_content 
    WHERE INSTR(post_content, 'A') > 0;
    

提交回复
热议问题