[英]Combining the many side of a many-to-one relationship into one field?
Two tables: books
and authors
. 两个表:
books
和authors
。 A book can have many authors, as in the case of a short story anthology. 一本书可以有很多作者,就像短篇小说选集一样。
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
book_id | authors_id
---------------------------
1 2
2 3
2 7
3 4
3 5
3 6
What I'd like to do is return a table where each row is a book, and the 'authors' field is a comma-separated list of all authors, eg 我想做的是返回一个表,其中每一行都是一本书,'authors'字段是所有作者的逗号分隔列表,例如
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
I've been playing around with GROUP BY
and concatenation functions, and I know the answer is there somewhere, but I just can't quite figure it out. 我一直在玩
GROUP BY
和连接函数,我知道答案就在那里,但我无法弄明白。 I can do it by juggling arrays and string joins around in my program itself but that's not the elegant solution I'm looking for. 我可以通过在程序本身中处理数组和字符串连接来实现它,但这不是我正在寻找的优雅解决方案。 A tip here would be appreciated.
这里的提示将不胜感激。
I'm using SQLite 3 if it's system-dependent. 我正在使用SQLite 3,如果它是依赖于系统的。
You have to join both tables, group by book and apply a group_concat
on the author namecolumn. 您必须逐个连接两个表,并在作者名称
group_concat
上应用group_concat。
The official documentation of the function is here 该功能的官方文档在这里
And here´s another example I´ve found in stackoverflow 这是我在stackoverflow中找到的另一个例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.