如何在MySQL中将两个相同的表连接在一起

时间:2013-04-23 04:22:43

标签: mysql sql

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

-- 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 ║
╚═════════╩════════════╩═══════════╝

如何处理此问题?

2 个答案:

答案 0 :(得分:4)

使用UNION:

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

答案 1 :(得分:0)

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

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