MySQL - 一对多查询,结果在单独的列中
MySQL - One to Many Query with results in separate columns
我有一个 table 的结构类似于下面提到的格式。
他们看起来像这样
本书
| ID | Title |
| 1 | A |
| 2 | B |
Book_Collaborators
| COLLAB_ID |BookID | Type |
| 1 | 1 | Author |
| 2 | 1 | Editor |
| 3 | 1 | Publisher |
合作者
| ID | Title |
| -- | ----- |
| 1 | D |
| 2 | E |
| 3 | F |
我需要以下格式的结果,其中作者、编辑和出版商等详细信息显示在不同的列中。
请注意,有时 Book_Collaborators table
中可能没有详细信息
| BOOK ID | Title | Author | Editor | Publisher |
| --------- | ----- |------ | ------ | --------- |
| 1 | A | D | E | F |
我想出了这个查询,但我不想多次加入同一个 table
select book.id as BookId, c.title as Author,c1.title as Editor
from Book book
left join Book_Collaborators bc on (book.id=bc.book_id and bc.type='Author')
left join Collaborators c on (bc.COLLAB_ID=c.id)
left join Book_Collaborators bc1 on (book.id=bc1.book_id and bc1.type='Editor')
left join Collaborators c1 on (bc1.COLLAB_ID=c1.id)
显示所有图书信息,无论是否在 book_collaborator table 中具有相关值。如果只需要相关值,则使用 INNER JOIN 而不是 LEFT JOIN。由于图书ID在图书中是唯一的table,因此在标题列使用聚合函数以避免它添加GROUP BY子句。
-- MySQL
SELECT b.id BOOK_ID
, MAX(b.title) Title
, MAX(CASE WHEN bc.btype = 'Author' THEN c.title END) Author
, MAX(CASE WHEN bc.btype = 'Editor' THEN c.title END) Editor
, MAX(CASE WHEN bc.btype = 'Publisher' THEN c.title END) Publisher
FROM Book b
LEFT JOIN Book_Collaborators bc
ON b.id = bc.book_id
LEFT JOIN Collaborators c
ON c.id = bc.collab_id
GROUP BY b.id
请从urlhttps://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=069dc205f176968d61d462ad3cad7568
检查
我有一个 table 的结构类似于下面提到的格式。 他们看起来像这样
本书
| ID | Title |
| 1 | A |
| 2 | B |
Book_Collaborators
| COLLAB_ID |BookID | Type |
| 1 | 1 | Author |
| 2 | 1 | Editor |
| 3 | 1 | Publisher |
合作者
| ID | Title |
| -- | ----- |
| 1 | D |
| 2 | E |
| 3 | F |
我需要以下格式的结果,其中作者、编辑和出版商等详细信息显示在不同的列中。
请注意,有时 Book_Collaborators table
中可能没有详细信息| BOOK ID | Title | Author | Editor | Publisher |
| --------- | ----- |------ | ------ | --------- |
| 1 | A | D | E | F |
我想出了这个查询,但我不想多次加入同一个 table
select book.id as BookId, c.title as Author,c1.title as Editor
from Book book
left join Book_Collaborators bc on (book.id=bc.book_id and bc.type='Author')
left join Collaborators c on (bc.COLLAB_ID=c.id)
left join Book_Collaborators bc1 on (book.id=bc1.book_id and bc1.type='Editor')
left join Collaborators c1 on (bc1.COLLAB_ID=c1.id)
显示所有图书信息,无论是否在 book_collaborator table 中具有相关值。如果只需要相关值,则使用 INNER JOIN 而不是 LEFT JOIN。由于图书ID在图书中是唯一的table,因此在标题列使用聚合函数以避免它添加GROUP BY子句。
-- MySQL
SELECT b.id BOOK_ID
, MAX(b.title) Title
, MAX(CASE WHEN bc.btype = 'Author' THEN c.title END) Author
, MAX(CASE WHEN bc.btype = 'Editor' THEN c.title END) Editor
, MAX(CASE WHEN bc.btype = 'Publisher' THEN c.title END) Publisher
FROM Book b
LEFT JOIN Book_Collaborators bc
ON b.id = bc.book_id
LEFT JOIN Collaborators c
ON c.id = bc.collab_id
GROUP BY b.id
请从urlhttps://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=069dc205f176968d61d462ad3cad7568
检查