Select Concat Substring and Replace in MySQL

2k views Asked by At

I have a .sql file that needs all the extra characters removed and just the text left. So anything inside the " ". An example of the TEXT field in the column is

a:1:{i:0;s:9:"test word here";}

a:1:{i:0;s:11:"test words here too";}

So I would want the words. test word here. and test words here too. To be all left in the text field.

I originally went with something like this.

  UPDATE `questions`
  SET answer = REPLACE(REPLACE(REPLACE(REPLACE(answer, 'a:1', ''), 's:4', ''), 'i:0', ''), ',', '')

But then quickly realized the s:4 has s:5, s:16 etc. So that wouldn't work. My next attempt was to use concat and just remove a certain amount of characters starting with a:1. I was able to do a working SELECT. But not able to get a REPLACE to work. Below you can see the working SELECT.

SELECT CONCAT('tt',
          SUBSTRING(`answer`, -LOCATE('a:1', `answer`)+15)
   ) from `questions`;

Here is my attempt at getting a REPLACE to work with it. But I'm stuck. I'm open to any suggestions, in case I'm going in the complete wrong direction here anyways.

SELECT CONCAT(REPLACE('tt',
          SUBSTRING(`answer`, -LOCATE('a:1', `answer`)+15))
   ) from `questions`;
2

There are 2 answers

1
Gordon Linoff On BEST ANSWER

How about substring_index()?

UPDATE `questions`
    SET answer = substring_index(substring_index(answer, '"', 2), '"', -1)
1
slaakso On

You could do something like this:

select substr(with_end, 1, locate('"', with_end )-1) as 'str'
from (
  select substr(answer, locate('"', answer )+1) 'with_end'
  from questions
) as q