1
以前我將作者姓名保存到我的書籍表中,這不是最佳做法。所以我把作者外包給一個單獨的表格,並通過數據透視表來加入數據。我的查詢是這樣的:如何處理從書籍表查詢中返回的多位作者
SELECT b.id, b.title, CONCAT(a.fname,' ' , a.lname) AS author_name, a.id as author_id
FROM books b
LEFT JOIN author_book ab ON b.id = ab.book_id
LEFT JOIN authors a ON ab.author_id = a.id
WHERE b.id = '406'
到目前爲止,一切工作正常,但我的查詢不僅返回一個行數據,但是他們兩個人 - 每個作者。
id | title | author_name | author_id
--------------------------------------------------------------------
406 | The world of the wheel of time | Robert Jordan | 2
406 | The world of the wheel of time | Teresa Patterson | 3
但我真的很想只輸出一本書有多個作者 - 而不是一本書的多本書。在這個例子中,這並不難,但是當我搜索短小的書籍時會發生什麼?涉及多達十幾位作者。然後,返回的結果可能看起來就像這個例子:
id | title | author_name | author_id
--------------------------------------------------------------------
103 | Here Be Monsters | M.T. Murphy | 12
103 | Here Be Monsters | S.M. Reine | 6
103 | Here Be Monsters | India Drummond | 182
103 | Here Be Monsters | Anabel Portillo | 643
103 | Here Be Monsters | Jeremy C. Shipp | 35
103 | Here Be Monsters | Samantha Anderson | 58
103 | Here Be Monsters | Sara Reinke | 26
521 | Science Fiction Megapack | Fritz Leiber | 19
521 | Science Fiction Megapack | C.M. Kornbluth | 27
521 | Science Fiction Megapack | Philip K. Dick | 24
521 | Science Fiction Megapack | E.C. Tubb | 46
521 | Science Fiction Megapack | John Glasby | 67
我可以嘗試使用GROUP BY ID或標題,但隨後筆者會迷路,但一個。 (一些PHP數組操作可能是一個解決方案?)。你會如何輸出這些數據,這樣每本書都會保留一個包含所有作者的實體?
哇哦,這是一個完美的解決方案!非常感謝你,邁克,你讓我的一天! – Hexodus 2013-04-03 22:12:57