1

I have two tables with the construction below. When I try to add to the books table I get an error that I cannot add or update a child row which I expected. I was hoping that a trigger could be created to add the publisher name to the publisher table before adding to the books table.

This is my first time working with a trigger and I am not sure what I am doing wrong and I can't find an example.

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;

and the trigger I am trying to create:

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

DELIMITER ;
4

1 回答 1

2

Replace books.publisher_name for 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 ;
于 2017-11-23T20:50:47.183 回答