2013-04-23 93 views
0

下面是我的數據庫架構三個表:如何連接兩個相同的表一起在MySQL

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

以下是我想要實現的內容:我需要將與該書相關聯的行(如果存在更多的行)添加到上面的選擇中,該表中的ID爲37,如果你願意,可以製作兩張桌子, :BOOK_AUTHORtemp_book_author也就是說,一個表就好像它們是一個表來開始:

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

我該如何解決這個問題?

+2

你是否需要'INSERT INTO BOOK_AUTHOR(book_id,author_id)SELECT book_id,Author_id FROm temp_book_author;'或者我誤解了 – Scotch 2013-04-23 04:25:56

+0

@Scotch:請添加它作爲答案,以便它可能被接受。 – 2013-04-23 04:39:17

+0

@RoneyMichael太晚了:) – Scotch 2013-04-23 05:53:47

回答

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

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