I have a table:
ID name
1 john, peter, ken
how can i separate the name column (which the value are being separated with comma delimited) into separate column using MYSQL?
ID name
1 john
1 peter
1 ken
I have a table:
ID name
1 john, peter, ken
how can i separate the name column (which the value are being separated with comma delimited) into separate column using MYSQL?
ID name
1 john
1 peter
1 ken
You could use a query like this:
SELECT
id,
n.digit,
name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ',', n.digit+1), ',', -1)
FROM
mytable
INNER JOIN
(SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) n
ON LENGTH(REPLACE(name, ',' , '')) <= LENGTH(name)-n.digit
(please notice that this will only separate up to 4 names).
Fiddle is here.
Explanation
I'm making use of a query that returns all numbers from 0 to 3 (you could use an indexed table with 10 or 100 numbers, for example):
SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
I'm then joining this number with mytable
, using this join conditions:
ON LENGTH(REPLACE(name, ',' , '')) <= LENGTH(name)-n.digit
which is a "dirty" way to check if the name column contains at least n.digit
names (I'm removing all commas, and I'm checking the difference in length with the full string).
Using SUBSTRING_INDEX you can get the part of the string at the left of the n.digit+1
comma:
SUBSTRING_INDEX(name, ',', n.digit+1)
and using one more SUBSTRING_INDEX with a negative parameter you can only keep the part of the string up to the first comma:
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ',', n.digit+1), ',', -1)
If you need to get thh data into mysql then you can create a php file using explode to create an array per id.
These may help:
How can I split a comma delimited string into an array in PHP?