触发器在插入子表时将值插入父表

时间:2017-11-23 20:05:04

标签: mysql triggers mysql-error-1452

我有两张表格,下面是结构。当我尝试添加到books表时,我收到一个错误,我无法添加或更新我期望的子行。我希望在添加到books表之前可以创建一个触发器来将发布者名称添加到发布者表中。

这是我第一次使用触发器而且我不确定我做错了什么而且我找不到一个例子。

create table publishers
    (name varchar(25) not null, 
    address varchar(55), 
    phone varchar(12),
    PRIMARY KEY(name)
    ) ENGINE = INNODB;

create table books
    (book_id int(4) not null auto_increment, 
    title varchar(40), 
    publisher_name varchar(25),
    primary key (book_id),
    foreign key (publisher_name) references publishers(name) ON UPDATE CASCADE ON DELETE CASCADE 
    ) ENGINE=INNODB;

和我想要创建的触发器:

DELIMITER ///
CREATE TRIGGER add_publisher BEFORE insert ON books
    FOR EACH ROW
    BEGIN
    INSERT INTO publishers(name) values (books.pubisher_name);
END;
///

DELIMITER ;

1 个答案:

答案 0 :(得分:1)

books.publisher_name 替换为 NEW.publisher_name

    DELIMITER ///
    CREATE TRIGGER add_publisher BEFORE insert ON books
        FOR EACH ROW
        BEGIN
        INSERT INTO publishers(name) values (NEW.publisher_name);
    END;
    ///
DELIMITER ;