如何处理从书籍表查询返回的多个作者

时间:2013-04-03 20:55:02

标签: php mysql database

以前我将作者姓名存储在我的书籍表中,这不是最佳做法。因此,我将作者外包给一个单独的表,并通过数据透视表加入数据。我的查询如下:

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或title,但作者会迷失但只有一个。 (一些php数组操作可能是一个解决方案?)。您将如何输出这些数据,以便每本书都与所有作者保持一个单一的实体?

1 个答案:

答案 0 :(得分:4)

您可能需要考虑使用GROUP_CONCAT(),如下所示:

SELECT
  b.id,
  b.title,
  GROUP_CONCAT(CONCAT(a.fname,' ' , a.lname)) AS author_names,
  GROUP_CONCAT(a.id) as author_ids
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'
GROUP BY b.id

这会给你输出像:

406 | The world of the wheel of time | Robert Jordan,Teresa Patterson     | 2,3