[英]Joining a m:n MySQL relation with every entity in own column
I'm working on a web application to manage my books and I'm currently confronted with a problem I can't solve. 我正在开发一个用于管理图书的网络应用程序,目前遇到无法解决的问题。
books
. books
。 The primary key is bookId
and each book can be written by 1 or more authors. bookId
,每本书可以由1个或多个作者编写。 name
which together with the primary key authorId
is stored in the table authors
. name
,该name
与主键authorId
一起存储在表authors
。 Every author can have written 1 or more books. books_authors
where the bookId
and the authorId
are stored as foreign keys to bookId
in books
and authorId
in authors
. books_authors
其中bookId
和authorId
存储为外键bookId
的books
和authorId
的authors
。 See here a shortened version of the relevant tables: 请在此处查看相关表格的缩写:
books
+--------+-------+-------------+
| bookId | title | numberPages |
+--------+-------+-------------+
| 1 | Alpha | 100 |
| 2 | Beta | 200 |
| 3 | Ceta | 150 |
+--------+-------+-------------+
authors
+----------+----------+
| authorId | name |
+----------+----------+
| 1 | John |
| 2 | Max |
| 3 | Gina |
| 4 | Marry |
+----------+----------+
books_authors
+--------+----------+
| bookId | authorId |
+--------+----------+
| 1 | 1 |
| 1 | 4 |
| 2 | 2 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
+--------+----------+
I need a SQL statement now that gives me back one single table like the following. 现在,我需要一条SQL语句,该语句可以给我返回一个如下所示的表。 Every book should only have one row and all authors should be in seperate columns.
每本书只应有一行,所有作者应放在不同的列中。 And exactly this is the problem for me in finding a solution as sometimes a book has one or two or three or ... authors.
对于我来说,这正是寻找解决方案的问题,因为有时一本书有一个或两个或三个或...作者。 So the statement should be "dynamic" in creating this "joined" table:
因此,在创建此“联接”表时,该语句应该是“动态的”:
Joined Table
+--------+-------+-------------+---------+---------+---------+
| bookId | title | numberPages | author1 | author2 | author3 |
+--------+-------+-------------+---------+---------+---------+
| 1 | Alpha | 100 | John | Marry | |
| 2 | Beta | 200 | Max | | |
| 3 | Ceta | 150 | Max | Gina | Marry |
+--------+-------+-------------+---------+---------+---------+
Thank you very much for your help! 非常感谢您的帮助!
I don't like your current expected output, because in the future we may encounter a book which has more than 3 authors. 我不喜欢您当前的预期输出,因为将来我们可能会遇到一本书,作者超过3名。 I suggest the following alternative:
我建议以下替代方法:
SELECT
b.bookId,
b.title,
b.numberPages,
GROUP_CONCAT(a.name ORDER BY a.authorId) authors
FROM books b
LEFT JOIN books_authors ba
ON b.bookId = ba.bookId
LEFT JOIN authors a
ON ba.authorId = a.authorId
GROUP BY
b.bookId;
This approach generates a CSV list of all authors of each book. 这种方法会生成每本书所有作者的CSV列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.