Search code examples
mysqldata-migration

Split table into two tables with foreign keys


I have one table: drupal.comments, with amongst others, the columns:

cid: primary key
uid: foreign key to users table, optional
name: varchar, optional
email: varchar, optional

The description says: UID is optional, if 0, comment made by anonymous; in that case the name/email is set.

I want to split this out into two tables rails.comments and rails.users, where there is always a user:

id: primary key
users_id:  foreign key, always set.

So, for each drupal.comment, I need to create either a new user from the drupal.comments.name/drupal.comments.email and a rails.comment where the rails.comment.users_id is the ID of the just created user.

Or, if username/email already exists for a rails.user, I need to fetch that users_id and use that on the new comment record as foreign key.

Or, if drupal.comment.uid is set, I need to use that as users_id.

Is this possible in SQL? Are queries that fetch from one source, but fill multiple tables possible in SQL? Or is there some (My)SQL trick to achieve this? Or should I simply script this in Ruby, PHP or some other language instead?


Solution

  • I searched further and found that, apparently, it is not possible to update/insert more then one table in a single query in MySQL.

    The solution would, therefore have to be scripted/programmed outside of SQL.