0

I have a table with one column :

Val A
Val B
Val C,Val B,Val D
Val A,Val F,Val A

My question how can i split the values after a specific character in this case "," so that i can have only one per row like this :

Val A
Val B
Val C
Val B
Val D
Val A
Val F
Val A

I don't if it's important but i'm using MySql Workbench. Thanks in advance.

7
  • Hi @rzss275 I have attached the link with the answer I believe you need... Commented Sep 17, 2020 at 10:45
  • Does this answer your question? how to create a query in sql to chop sentences into words and add them to new table with their frequency or How to split values in single strings using comma Commented Sep 17, 2020 at 10:47
  • Never, ever store data as comma separated items! It will only cause you lots of trouble. Commented Sep 17, 2020 at 10:48
  • 1
    @VBoka thanks for the link and for your help ,i found in there one solution that works for me. Commented Sep 17, 2020 at 11:21
  • @jarlh This is how it's ,it's not my decision to have data like that. Commented Sep 17, 2020 at 11:22

1 Answer 1

0

You can use substring_index(). One method is:

select substring_index(col, ';', 1)
from t
union all
select substring_index(substring_index(col, ';', 2), ';', -1)
from t
where col like '%;%'
union all
select substring_index(substring_index(col, ';', 3), ';', -1)
from t
where col like '%;%;%';

You need to add a separate subquery up to the maximum number of elements in any row.

EDIT:

I don't really like the answers in the duplicate. I would recommend a recursive CTE:

with recursive cte as (
      select col as part, concat(col, ',') as rest, 0 as lev
      from t
      union all
      select substring_index(rest, ',', 1),
             substr(rest, instr(rest, ',') + 1),
             lev + 1
      from cte
      where rest <> '' and lev < 5 
     )
select part
from cte
where lev > 0;

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

That would be a problem because there is a lot of data and i don't the maximum number of elements in a row.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.