MySQL:将连接后的多个值组合到一个结果列中

Ack*_*Ack 11 mysql sql left-join group-concat

我有一个带有发布表的数据库,每个发布可以有多个作者存储在不同的表中.我想查询数据库,在一列中给出一个出版物标题列表,在第二列中给出该出版物的合并作者.

SELECT p.`id`, p.`title`, a.`fullname` 
from `publications` p 
LEFT JOIN `authors` a on a.`publication_id` = p.`id`;
Run Code Online (Sandbox Code Playgroud)

这当然给了我许多作者多次出版的标题.

id   title              fullname
--   -----              --------
1    Beneath the Skin   Sean French
1    Beneath the Skin   Nicci Gerrard
2    The Talisman       Stephen King
2    The Talisman       Peter Straub
Run Code Online (Sandbox Code Playgroud)

对id进行分组,每个标题给我一个作者:

SELECT p.`id`, p.`title`, a.`fullname` 
from `publications` p 
LEFT JOIN `authors` a on a.`publication_id` = p.`id` 
GROUP BY a.`id`;

id   title              fullname
--   -----              --------
1    Beneath the Skin   Sean French
2    The Talisman       Stephen King
Run Code Online (Sandbox Code Playgroud)

我正在寻找的结果是这样的:

id   title              fullname
--   -----              --------
1    Beneath the Skin   Sean French, Nicci Gerrard
2    The Talisman       Stephen King, Peter Straub
Run Code Online (Sandbox Code Playgroud)

我认为答案应该在使用GROUP_CONCAT时找到,但我能得到的唯一结果是所有作者的一个结果行:

SELECT p.`id`, p.`title`, GROUP_CONCAT(a.`fullname`) from `publications` p 
LEFT JOIN `authors` a on a.`publication_id` = p.`id` 
GROUP BY a.`id`;

id   title              fullname
--   -----              --------
1    Beneath the Skin   Sean French, Nicci Gerrard, Stephen King, Peter Straub
Run Code Online (Sandbox Code Playgroud)

在连接后使用GROUP_CONCAT给我一个"每个派生表必须有自己的别名"错误.

SELECT p.`id`, p.`title`, a.`fullname` 
FROM `publications` p 
LEFT JOIN (SELECT GROUP_CONCAT(a.`fullname`) FROM `authors` a) ON a.`publication_id` = p.`id`;
Run Code Online (Sandbox Code Playgroud)

有线索吗?

Stu*_*tLC 12

您需要按SELECT列中的所有非聚合列进行分组(并且显式地,不是作者ID,因为author.id不是选择列表的一部分):

SELECT p.`id`, p.`title`, GROUP_CONCAT(a.`fullname` separator ', ')
from `publications` p 
LEFT JOIN `authors` a on a.`publication_id` = p.`id` 
GROUP BY p.`id`, p.`title`;
Run Code Online (Sandbox Code Playgroud)