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

4

1 回答 1

5

您可能要考虑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
于 2013-04-03T20:58:31.007 回答