1

这是我的数据库架构中的三个表:

-- 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_authortemp_book_author,即一张表,就好像它们是一张表一样开始:

╔═════════╦════════════╦═══════════╗
║ book_id ║ first_name ║ last_name ║
╠═════════╬════════════╬═══════════╣
║      37 ║     Ernest ║ Hemingway ║
║      37 ║       Walt ║   Whitman ║
║      37 ║       Mark ║     Twain ║
╚═════════╩════════════╩═══════════╝

我该如何解决这个问题?

4

2 回答 2

5

使用联合:

SET    @BOOK_ID = 37;
SELECT @BOOK_ID AS book_id,
       a.last_name,
       a.first_name
FROM   (SELECT * FROM book_author
        UNION
        SELECT * FROM temp_book_author) AS ba
       LEFT JOIN author AS a
              ON ba.author_id = a.author_id
WHERE  book_id = @BOOK_ID;

您还可以创建一个自动合并两个表的表:

CREATE TABLE union_book_author (book_id int, author_id int)
ENGINE = MERGE
UNION = (book_author, temp_book_author);

然后,您可以union_book_author在查询中使用。

于 2013-04-23T04:45:21.340 回答
0

我同意 Scotch 的评论,理想情况下您应该将 temp_book_author 中的数据插入 book_author 中,然后从该表中进行选择,但如果您有不想这样做的原因,那么您需要使用 sql 命令' union '。

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
UNION
select t.book_id, a1.last_name, a1.firstname
from temp_book_author as t
left join author as a1 on t.author_id = a1.author_id
where t.book_id = @BOOK_ID
于 2013-04-23T04:45:14.767 回答