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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With