CSV to Rowe

Hi experts

In MySQL, how do I SELECT a CSV list as separate rows?

For example, let's say I have a clients table with 2 fields

name - mark
services - 4,6,12

How can I return 3 rows ask
Mark  4
Mark 6
Mark 12

Thank you
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulEE Topic AdvisorCommented:
You should NOT store the data that way... that's the awful truth.
0
PortletPaulEE Topic AdvisorCommented:
Here is a way to do it:
    CREATE TABLE customers
        (`name` varchar(40), `services` varchar(60))
    ;
        
    INSERT INTO customers
        (`name`, `services`)
    VALUES
        ('mark', '4,6,12')
    ;

Open in new window

   
    SELECT 
      name
    , SUBSTRING_INDEX(SUBSTRING_INDEX(services, ',', n.digit+1), ',', -1) service
    FROM customers
    INNER JOIN (
       SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
       ) n ON LENGTH(REPLACE(services, ',' , '')) <= LENGTH(services)-n.digit
    

Open in new window


    | name | service |
    |------|---------|
    | mark |       4 |
    | mark |       6 |
    | mark |      12 |

Open in new window


See: http://sqlfiddle.com/#!9/b557e0/4
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
theGhost_k8Database ConsultantCommented:
Despite above query from Paul works awesome for the sample dataset; I'd like to pitch in the idea I used long back when this was once a requirement. Have a look at this article of splitting delimited column values to rows.

All you need to do is change the cursor query as per your table columns "SELECT name,services from customers;" and specify delimiter ","
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.