berkes
berkes

Reputation: 27563

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?

Upvotes: 1

Views: 2301

Answers (2)

Ike Walker
Ike Walker

Reputation: 65567

You could do this with a TRIGGER.

Here's some pseudo-code to illustrate this technique:

DELIMITER $$

DROP TRIGGER IF EXISTS tr_b_ins_comments $$

CREATE TRIGGER tr_b_ins_comments BEFORE INSERT ON comments FOR EACH ROW BEGIN
  DECLARE v_uid INT DEFAULT NULL;

  /* BEGIN pseudo-code */
  IF (new.uid IS NULL)
  THEN
    -- check for existing user with matching name and email address
    select user_id
    into v_uid
    from your_user_table
    where name = new.name 
    and email = new.email;

    -- if no match, create a new user and get the id
    IF (v_uid IS NULL)
    THEN
      -- insert a new user into the user table
      insert into your_user_table ...

      -- get the new user's id (assuming it's auto-increment)
      set v_uid := LAST_INSERT_ID();
    END IF;

    -- set the uid column
    SET new.uid = v_uid;
  END IF;

  /* END pseudo-code */
END $$

DELIMITER ;

Upvotes: 2

berkes
berkes

Reputation: 27563

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.

Upvotes: 0

Related Questions