MySQL触发器将数据插入到不同的DB中

时间:2011-08-19 22:44:50

标签: mysql

听起来很简单......我花了几个小时才得到第一部分工作,这是一个mysql触发器到另一个数据库。现在我想变聪明并加入几张桌子。

我有两个主表PROJ和COMP。两者共享id。插入PROJ时,我想将一些NEW.PROJ信息和一些COMP信息插入到db.table axis.axis_data

中的一行中。

有人请帮我用TRIGGER做SELECT...INSERT。我可能会对这个问题感到满意

我的工作触发器。

DELIMITER $$

DROP TRIGGER IF EXISTS `rate_data_trigger` $$

CREATE TRIGGER rate_data_trigger
    BEFORE INSERT on PROJ FOR EACH ROW
    BEGIN

        INSERT INTO axis.axis_data
            (projinfo_table_id, rate_user, name,
             property_owner, property_address, property_city,
             property_state, property_zip, property_phone,
             rating_date, rating_type, rating_reason, rating_number
            )  

        VALUES
            (NEW.id, user(), NEW.BLGNAME,
             NEW.POWNER, NEW.STREET, NEW.CITY,
             NEW.STATE, NEW.ZIP, NEW.PHONE,
             NEW.RATDATE, NEW.RATTYPE, NEW.RATREAS, NEW.RATNGNO
            );
    END$$
DELIMITER ;

1 个答案:

答案 0 :(得分:1)

只需在select语句中使用以下语法:

INSERT INTO axis.axis_data
        (projinfo_table_id, rate_user, name,
         property_owner, property_address, property_city,
         property_state, property_zip, property_phone,
         rating_date, rating_type, rating_reason, rating_number,
         field1, field2
        )  

    SELECT NEW.id, user(), NEW.BLGNAME,
         NEW.POWNER, NEW.STREET, NEW.CITY,
         NEW.STATE, NEW.ZIP, NEW.PHONE,
         NEW.RATDATE, NEW.RATTYPE, NEW.RATREAS, NEW.RATNGNO,
         c.field1, c.field2
    FROM COMP c WHERE c.id = NEW.id

如果COMP在PROJ中并不总是有相应的记录,您可以使用SELECT ... FROM DUAL LEFT JOIN COMP c ON c.id = NEW.id