I have some data in a table like so:
product_id | categories
----------------+-------------
10 | 9,12
11 | 8
12 | 11,18,5
I want a select statement that would produce this output:
product_id | category_id
----------------+-------------
10 | 9
10 | 12
11 | 8
12 | 11
12 | 18
12 | 5
I don't know how to phrase this scenario to be able to google it.
Best Answer
What you are looking for is the inverse of a GROUP BY aggregate query using the GROUP_CONCAT. If you are willing to store the results in a temp table, I got just the thing.
First, here is the code to use you sample data in a table called
prod
and a temp table calledprodcat
to hold the results you are looking for.Here it is loaded
OK, you need query to put together each product_id with each category. Here it is:
Here it is executed
Let me run each line by hand
OK, good. The queries work. Did the prodcat table populate properly?
OK Great. It has the data.
To be honest, I think SQL Server can perform all of this in a single pivot query without a handmade temp table.
I could have taken it to another level and concatenated all the queries into a single query, but the SQL would have been insanely long. If your actual query had 1000s of rows, a single MySQL would not have been practical.
Instead of running the 3 INSERT queries by hand, you could echo the 3 INSERT queries to a text file and execute it as a script. Then, you have a table with the products and categories combinations individually written.