mysql inserting into 2 tables at once that have pr

2019-04-14 21:52发布

问题:

I have two tables

books table

  • ID (PK)
  • Title
  • Author
  • Genre
  • ISBN
  • Price
  • publisher
  • Year

bookAwards table

  • ID (FK) -- referencing Books.ID
  • Awardname
  • Year

ID of bookAwards is foreign key of ID in books table.

How can I insert into books table at the same time into bookAwards table?

When I am trying to insert into books table it gives the error that foreign key causes?

I want to insert into books table the values and then an awardname with a year into bookAwards?

Any help will be much appreciated.

回答1:

You can use STORED PROCEDURE on this so you will only call once from the application level. Example,

DELIMITER $$
CREATE PROCEDURE InsertBook
(
    IN _Title INT,
    IN _AwardName VARCHAR(35),
    IN _Year INT
)
BEGIN
    INSERT INTO Books (Title)
    VALUES(_Title);

    -- since the ID is set as AUTO_INCREMENT
    -- there are two ways to do how you can get the ID 
    -- from the Books Table and insert it 
    -- on BookAwards

    -- FIRST WAY
    -- by using LAST_INSERT_ID()
    SET @last_ID = LAST_INSERT_ID();

    -- SECOND WAY
    -- by using MAX()
    -- SET @last_ID = (SELECT MAX(ID) FROM Books);


    INSERT INTO BookAwards(ID, AwardName, Year)
    VALUES (@last_ID, _AwardName, _Year);
END $$
DELIMITER ;

And on the application level or on any sources that you want to call this procedure,

CALL InsertBook('Lost Art', 'Best in Churva', 2013);

For security purposes, you can still parameterized the procedure, eg

CALL InsertBook(?, ?, ?);