使用外键将表拆分为两个表

时间:2011-03-15 14:09:03

标签: mysql data-migration

我有一个表:drupal.comments,其中包括列:

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

描述说:UID是可选的,如果为0,则匿名发表评论;在这种情况下,名称/电子邮件已设置。

我想将其拆分为两个表rails.commentsrails.users,其中总有一个用户:

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

因此,对于每个drupal.com,我需要创建drupal.comments.name/drupal.comments.email中的新用户和rails.comment,其中rails.comment.users_id是just的ID创建用户。

或者,如果rails.user已经存在用户名/电子邮件,我需要获取那个users_id并将其作为外键用在新的评论记录中。

或者,如果设置了drupal.comment.uid,我需要将其用作users_id。

这在SQL中可行吗? 是从一个源获取但是在SQL中填充多个表的查询吗?或者是否有一些(我的)SQL技巧可以实现此目的?或者我应该简单地用Ruby,PHP或其他语言编写脚本?

2 个答案:

答案 0 :(得分:2)

您可以使用TRIGGER执行此操作。

这里有一些伪代码来说明这种技术:

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 ;

答案 1 :(得分:0)

我进一步搜索并发现,显然,在MySQL的单个查询中它是not possible to update/insert more then one table

因此,解决方案必须在SQL之外编写脚本/编程。

相关问题