sql - 将多对一关系的多个方面组合到一个字段中?

标签 sql sqlite

两个表:booksauthors。一本书可以有很多作者,就像短篇小说选集一样。

书籍

id    |    title
--------------------
1        The Time Machine Did It
2        Snakes in Suits
3        Ghost in the Wires

作者

id    |    name
------------------------
1        Stephen King
2        John Swartzwelder
3        Robert D. Hare
4        Kevin Mitnick
5        William L. Simon
6        Steve Wozniak
7        Paul Babiak

books_authors_link

book_id    |    authors_id
---------------------------
1                2
2                3
2                7
3                4
3                5
3                6

我想做的是返回一个表,其中每一行都是一本书,“作者”字段是所有作者的逗号分隔列表,例如

查询结果

title                    |    authors
---------------------------------
The Time Machine Did It    John Swartzwelder
Snakes in Suits            Robert D. Hare, Paul Babiak
Ghost in the Wires         Kevin Mitnick, William L. Simon, Steve Wozniak

我一直在研究 GROUP BY 和连接函数,我知道答案就在某处,但我就是不太明白。我可以通过在我的程序本身中使用数组和字符串连接来做到这一点,但这不是我正在寻找的优雅解决方案。此处提供提示将不胜感激。

如果它依赖于系统,我正在使用 SQLite 3。

最佳答案

您必须连接两个表,按书分组并在作者姓名列上应用 group_concat

该函数的官方文档为here

here´s another example I´ve found in stackoverflow

关于sql - 将多对一关系的多个方面组合到一个字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868810/

相关文章:

sql - 计算 ID 满足条件的次数

unit-testing - 使用 PDO Sqlite 内存数据库进行 PHPUnit 测试

sql - 在 postgreSQL 查询的 where 子句中使用文本文件

python - 谷歌应用引擎 : Intro to their Data Store API for people with SQL Background?

MySQL 左连接错误 #1064

python - 在 PostgreSQL 中检查 python 数组(或 csv)是否有重复项,在相邻的列中显示状态

sql - 创建、更新、删除的通用术语

python - sqlite3.programmingerror 提供的绑定(bind)数量不正确

SQL 查询使用多列的顶级条目

c - 在没有额外查询的情况下获取 SQLite3 中受 UPDATE 影响的行