How to replace every other instance of a particular character in a MySQL string?

前端 未结 5 1260
梦毁少年i
梦毁少年i 2021-01-07 22:49

How to replace value in mysql column by query like, Column is options and its of type varchar(255)

From

id   options
1    A         


        
5条回答
  •  天命终不由人
    2021-01-07 23:07

    Not using stored procedures, I would do it in 2 steps:

    1. Insert the comma at the second occurrence of the pipe character:

      update options set options = insert(options, locate('|', options, locate('|', options) + 1), 1, ',');
      
    2. Insert the remaining commas - execute the query N times:

      update options set options = insert(options, locate('|', options, locate('|', options, length(options) - locate(',', reverse(options)) + 1) + 1), 1, ',');
      

      where N =

      select max(round(((length(options) - length(replace(options, '|', ''))) - 1 ) / 2) - 1) from options;
      

      (or don't bother with counting and continue to execute the query as long as it doesn't tell you "0 rows affected")

    Checked with this set of data:

    id   options
    1    A|10|B|20|C|30
    2    A|Positive|B|Negative
    3    A|10|B|20|C|30|D|40|E|50|F|60
    4    A|Positive|B|Negative|C|Neutral|D|Dunno
    

    results in:

    id   options
    1    A|10,B|20,C|30
    2    A|Positive,B|Negative
    3    A|10,B|20,C|30,D|40,E|50,F|60
    4    A|Positive,B|Negative,C|Neutral,D|Dunno
    

    (I'll provide an explanation later)

提交回复
热议问题