mysql inserting into 2 tables at once that have primary key and foreign key

◇◆丶佛笑我妖孽 提交于 2019-12-06 10:43: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(?, ?, ?);


来源:https://stackoverflow.com/questions/15725630/mysql-inserting-into-2-tables-at-once-that-have-primary-key-and-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!