下面是我的數據庫架構三個表:如何連接兩個相同的表一起在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_AUTHOR和temp_book_author也就是說,一個表就好像它們是一個表來開始:
╔═════════╦════════════╦═══════════╗
║ book_id ║ first_name ║ last_name ║
╠═════════╬════════════╬═══════════╣
║ 37 ║ Ernest ║ Hemingway ║
║ 37 ║ Walt ║ Whitman ║
║ 37 ║ Mark ║ Twain ║
╚═════════╩════════════╩═══════════╝
我該如何解決這個問題?
你是否需要'INSERT INTO BOOK_AUTHOR(book_id,author_id)SELECT book_id,Author_id FROm temp_book_author;'或者我誤解了 – Scotch 2013-04-23 04:25:56
@Scotch:請添加它作爲答案,以便它可能被接受。 – 2013-04-23 04:39:17
@RoneyMichael太晚了:) – Scotch 2013-04-23 05:53:47