回答

收藏

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

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

我有一个用于发布的数据库,每个表可以有多个作者存储在不同的表中。我想查询数据库,以便在第一列中提供出版物标题列表,并在第二列中提供出版物。$ H" h4 t4 Z. ]% B* F0 P3 R
SELECT p.`id`,p.`title`,a.`fullname` from `publications` p LEFT JOIN `authors` a on a.`publication_id` = p.`id`;当然,这使我多次获得了许多作者的出版物标题。
6 ?0 N. I3 Y1 t$ mid   title              fullname--   -----              --------1    Beneath the Skin   Sean French1    Beneath the Skin   Nicci Gerrard2    The Talisman       Stephen King2    The Talisman       Peter Straub按ID分组后,每个标题都给了我一个作者:
# C; S' O8 p& b7 C: I% MSELECT 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我正在寻找的结果是:9 u" o' Q4 A# Q, K0 ?: m
id   title              fullname--   -----              --------1    Beneath the Skin   Sean French,Nicci Gerrard2    The Talisman       Stephen King,Peter Straub我觉得应该用GROUP_CONCAT找到答案,但我唯一能得到的结果是所有作者的结果:
- l! Q: S& J; j; I: O$ h# V: X0 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给我一个每个派生表都必须有自己的别名的错误。+ y+ V2 l0 W- ]0 |, k: m
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`;有什么线索吗?! ?: I2 e0 Q3 D% g
                                                                . S, [; Q! U/ T
    解决方案:                                                                , T8 ?9 U  W1 J6 K: y5 K# j
                                                                您需要对SELECT中间的所有非聚合列都被分组(并且很明显,不是作者ID分组,因为author是GROUP_CONCAT部分):7 F* H0 m4 A3 d/ R  J# h' f# Y3 K
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`;
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则