Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL CSV Row to multiple Rows

I need to migrate an old database to my new one. Unfortunately the guy who wrote the old database created an n,n relation using a field with comma separated foreign keys.

I would like to write a mysql query (maybe using insert into ... select) that splits those comma seperated foreign keys so that i can build a table where each row is a foreign key.

Is this possible?

like image 549
Konstantin Weitz Avatar asked Sep 13 '26 19:09

Konstantin Weitz


1 Answers

It's not straightforward to do this in pure SQL. It will be easiest to retrieve each record in turn using a programming language of your choice and insert the many-to-many join table records based on the comma separated field. The following pseudo code suggests an approach that you might use:

for each (id, csv_foreign_keys) in source_rows do
    foreign_keys = split ',', csv_foreign_keys

    for each fk in foreign_keys do
        insert (id, fk) into many-to-many link table

Once you've done this, the existing column holding the comma separated foreign keys can be removed.

like image 157
a'r Avatar answered Sep 15 '26 10:09

a'r