tags:

views:

90

answers:

2

I have an unnormalized table with a column containing a comma separated list that is a foreign key to another table:

+----------+-------------+   +--------------+-------+
| part_id  | material    |   | material_id  | name  |
+----------+-------------+   +--------------+-------+
|      339 | 1.2mm;1.6mm |   |            1 | 1.2mm |
|      970 | 1.6mm       |   |            2 | 1.6mm |
+----------+-------------+   +--------------+-------+

I want to read this data into a search engine that offers no procedural language.

So is there a way to either make a join on this column or run a query on this data that inserts appropriate entries into a new table? The resulting data should look like this:

+---------+-------------+
| part_id | material_id |
+---------+-------------+
|     339 |           1 |
|     339 |           2 |
|     970 |           2 |
+---------+-------------+

I could think of a solution if the DBMS supported functions returning a table but MySQL apparently doesn't.

A: 

This might help get you started, it splits a field's value and places the values in a temporary table.

http://forge.mysql.com/tools/tool.php?id=4 (click on the Show Highlighted Code tab)

bemace
A: 

I've answered two similar questions in as many days but not had any responses so I guess people are put off by the use of the cursor but as it should be a one off process I personally dont think that matters.

As you stated MySQL doesnt support table return types yet so you have little option other than to loop the table and parse the material csv string and generate the appropriate rows for part and material.

The following posts may prove of interest:

http://stackoverflow.com/questions/3928325/split-keywords-for-post-php-mysql/3929161#3929161

http://stackoverflow.com/questions/3908966/mysql-procedure-to-load-data-from-staging-table-to-other-tables-need-to-split-up/3909888#3909888

Rgds

f00
Not sure if you can do it without a loop, unless there is a preset maximum number of values that can be in the comma delimited values...you're sort of forced to a loop
M.E.
Yes you'll have to loop - as stated.
f00
Not the nicest solution because it takes the problem from the set theretical level to the procedural level and therefore can only be used as preparation, not in realtime (answers my "or", not my "either" question) but at least it works. Thanks. :)
AndreKR
that's causality for ya - crappy db design leads to crappy procedural fix :P
f00
Heh, well put f00. @AndreKR - it's a csv field in a single column, the problem you've posed never was on the set theorectical level unfortunately. You got a procedural answer to a procedural question. I guess if there had been a limit to the number of values in that csv column (max of 10?) you could potentially do a set based solution. May want to normalize your database...
M.E.