mysql 列值合并,MySQL:将联接后的多个值合并到一个结果列中

I have a database with a table for publications, each of which can have multiple authors that are stored in a different table. I'd like to query the database into giving me a list of publication titles in one column, and the combined authors for that publication in the second.

SELECT p.`id`, p.`title`, a.`fullname`

from `publications` p

LEFT JOIN `authors` a on a.`publication_id` = p.`id`;

This of course gives me multiple times the publication title for as many authors.

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

Grouping on id gives me one author per title:

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

The result I'm looking for is this:

id title fullname

-- ----- --------

1 Beneath the Skin Sean French, Nicci Gerrard

2 The Talisman Stephen King, Peter Straub

I think the answer should be found in using GROUP_CONCAT, but the only result I'm able to get is one result row with all authors:

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

And using GROUP_CONCAT after the join gives me an "Every derived table must have its own alias" error.

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`;

Any clues?

解决方案

You need to group by all of the non-aggregated columns in the SELECT columns (and explicitly, not the author id, because author.id is not part of the select list):

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`;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值