以前,我把作者的名字存储在我的图书表中,这不是最好的做法。所以我将作者外包到一个单独的表中,并通过pivot表连接数据。我的查询如下:
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
我可以尝试使用组的身份证或标题,但这样作者就会失去一个。(一些php数组操作可能是一个解决方案?)。如何输出这些数据,以便每本书都与所有作者保持一个实体?
最佳答案
您可能需要考虑这样使用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