我有两张桌子
书籍表
bookAwards表
bookAwards的ID是书籍表中ID的外键。
如何在bookAwards表中同时插入books表?
当我尝试插入books表时,它会给出外键导致的错误吗?
我想在book表中插入值,然后将一年的奖励名称插入bookAwards?
非常感谢任何帮助。
答案 0 :(得分:2)
您可以对此使用STORED PROCEDURE
,因此您只能从应用程序级别调用一次。例如,
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 ;
在应用程序级别或您要调用此过程的任何来源上
CALL InsertBook('Lost Art', 'Best in Churva', 2013);
出于安全考虑,您仍然可以参数化该过程,例如
CALL InsertBook(?, ?, ?);