这是我的数据库架构中的三个表:
-- Table where I store authors
SELECT author_id, first_name, last_name FROM author;
╔═══════════╦════════════╦═══════════╗
║ author_id ║ first_name ║ last_name ║
╠═══════════╬════════════╬═══════════╣
║ 1 ║ Ernest ║ Hemingway ║
║ 2 ║ Walt ║ Whitman ║
║ 3 ║ Mark ║ Twain ║
║ ... ║ ... ║ ... ║
╚═══════════╩════════════╩═══════════╝
-- Junction-table to keep track of books and their respective authors
SELECT book_id, author_id FROM book_author;
╔═════════╦═══════════╗
║ book_id ║ author_id ║
╠═════════╬═══════════╣
║ 37 ║ 1 ║
║ 37 ║ 2 ║
║ ... ║ ... ║
╚═════════╩═══════════╝
-- Temporary table to store, once again, books and their respective authors
-- but only for updating book purposes. The table is identical in its structure
-- to the book_author table
SELECT book_id, author_id FROM temp_book_author;
╔═════════╦═══════════╗
║ book_id ║ author_id ║
╠═════════╬═══════════╣
║ 37 ║ 3 ║
║ ... ║ ... ║
╚═════════╩═══════════╝
现在,我可以使用下面的查询来获得以下结果:
SET @BOOK_ID = 37;
SELECT @BOOK_ID AS book_id,
a.last_name,
a.first_name
FROM book_author AS ba
LEFT JOIN author AS a
ON ba.author_id = a.author_id
WHERE book_id = @BOOK_ID;
╔═════════╦════════════╦═══════════╗
║ book_id ║ first_name ║ last_name ║
╠═════════╬════════════╬═══════════╣
║ 37 ║ Ernest ║ Hemingway ║
║ 37 ║ Walt ║ Whitman ║
╚═════════╩════════════╩═══════════╝
这是我想要实现的目标:我需要将与从temp_book_author表中 ID 为 37 的书籍相关联的行(或行,如果有更多行)添加到上面的选择中,或者,如果你愿意, 有点制作两张表,book_author和temp_book_author,即一张表,就好像它们是一张表一样开始:
╔═════════╦════════════╦═══════════╗
║ book_id ║ first_name ║ last_name ║
╠═════════╬════════════╬═══════════╣
║ 37 ║ Ernest ║ Hemingway ║
║ 37 ║ Walt ║ Whitman ║
║ 37 ║ Mark ║ Twain ║
╚═════════╩════════════╩═══════════╝
我该如何解决这个问题?