回答

收藏

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

技术问答 技术问答 253 人阅读 | 0 人回复 | 2023-09-14

我有一个用于发布的数据库,每个表可以有多个作者存储在不同的表中。我想查询数据库,以便在第一列中提供出版物标题列表,并在第二列中提供出版物。& t, Z. V" ]( P) Q( h9 C; b! x
SELECT p.`id`,p.`title`,a.`fullname` from `publications` p LEFT JOIN `authors` a on a.`publication_id` = p.`id`;当然,这使我多次获得了许多作者的出版物标题。
$ M7 i' `9 [, p) {* B# y# g2 U9 U; Pid   title              fullname--   -----              --------1    Beneath the Skin   Sean French1    Beneath the Skin   Nicci Gerrard2    The Talisman       Stephen King2    The Talisman       Peter Straub按ID分组后,每个标题都给了我一个作者:
( J% v$ v# j* x$ Z" ESELECT 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 French2    The Talisman       Stephen King我正在寻找的结果是:2 y8 g  {8 x' H/ d3 I0 N2 S' v
id   title              fullname--   -----              --------1    Beneath the Skin   Sean French,Nicci Gerrard2    The Talisman       Stephen King,Peter Straub我觉得应该用GROUP_CONCAT找到答案,但我唯一能得到的结果是所有作者的结果:
: f. _* v$ Q" G6 m/ xSELECT 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连接后使用GROUP_CONCAT给我一个每个派生表都必须有自己的别名的错误。8 c% P4 |# ?7 q9 |
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`;有什么线索吗?6 q3 ?, M; [" A6 v
                                                                # P  y( n0 s8 k4 F7 c& `; t. F# Y
    解决方案:                                                                , ^! D( ]2 m! m5 H0 Y
                                                                您需要对SELECT中间的所有非聚合列都被分组(并且很明显,不是作者ID分组,因为author是GROUP_CONCAT部分):
- A! Z- {' _" c7 v  d  uSELECT 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`;
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则