I have to split a column in MySQL table on each occurrence of a pattern say ":" and "," into multiple rows.
Here is how the column data looks :-
Column_1
page1:message1,page2:message2,page3:message3,page4:message4
I want to show data like this :-
Column_2 Column_1
page1 message1
page2 message2
page3 message3
page4 message4
I have tried looking to REGEXP_REPLACE() and SUBSTRING_INDEX() MySQL functions but couldn’t form a query to achieve this.
Someone please help on this.
2
Answers
You can use a cte to get a row for each occurence of a row with an index
This will give you a result as
with that you can now just grab the n-th occurence of the part delimited with , and just split that part into two columns
and you get
If your MySQL version doesn’t support windows function you can create an numbers table (with the maximum length of your string) as follows :
Then follow a two step process.
First, divide your string with comma using:
You will get a result like this:
Second, divide the rows using
:
as below:https://dbfiddle.uk/acWncQ8y