Hex*_*dus 1 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'
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切正常,但我的查询不仅返回一行数据,还返回其中两个数据 - 每个作者一个。
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
Run Code Online (Sandbox Code Playgroud)
但我真的只想输出一本书有多个作者 - 而不是多本书有一个作者。在这个例子中,这样做并不难,但是当我搜索带有短篇小说的书籍时会发生什么?多达数十位作者参与其中。然后返回的结果可能看起来像在这个例子中:
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
Run Code Online (Sandbox Code Playgroud)
我可以尝试使用 GROUP BY id 或 title 但这样作者就会迷失其中一个。(一些 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
Run Code Online (Sandbox Code Playgroud)
那会给你这样的输出:
406 | The world of the wheel of time | Robert Jordan,Teresa Patterson | 2,3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1030 次 |
| 最近记录: |