2011-03-15 57 views
1

我有一个表: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.comment,我需要创建一个Drupal的无论是新用户.comments.name/drupal.comments.email和rails.com,其中rails.comment.users_id是刚刚创建的用户的ID。或者,如果用户名/电子邮件已存在for rails.user,我需要获取users_id并将它作为外键用于新评论记录。

或者,如果设置了drupal.comment.uid,我需要使用它作为users_id。

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

回答

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 ; 
+0

如果我的理解是正确的,我只需要一个记录写入到'comments',与其他电子邮件,名称列,它就会触发触发? – berkes 2011-03-15 22:14:34

+0

这就是主意。您需要重新编写触发器以适应您的特定模式,但我试图在必要时使用伪代码为您提供有用的框架,并将插入语法留给您。 – 2011-03-15 22:29:37