SQL:3个表(book,author,book_author)

Mik*_*ail 7 mysql sql join concatenation

我的MySQL数据库中有3个表,它们具有以下结构:

书桌:

     BOOK
---------------
book_id | title
---------------
   1    |   A
   2    |   B
Run Code Online (Sandbox Code Playgroud)

作者表:

     AUTHOR
----------------
author_id | name
----------------
     1    | John
     2    | Bush
     3    | Alex
     4    | Bob
Run Code Online (Sandbox Code Playgroud)

然后我有一个联合表,它建立了表和作者之间的多对多关系,这意味着一本书可以由许多作者撰写(合着,即),作者可以有很多书或者他她写了.

    BOOK_AUTHOR
--------------------
book_id |  author_id
--------------------
   1    |     1
   1    |     2
   1    |     3
   1    |     4
   2    |     3
   2    |     4
Run Code Online (Sandbox Code Playgroud)

是否可以通过SQL或MySQL使DBMS输出如下内容:

 book_id |  title  |       authors
------------------------------------------
    1    |    A    | John, Bush, Alex, Bob
    2    |    B    | Alex, Bob
Run Code Online (Sandbox Code Playgroud)

输出中的作者行是与特定书籍相关的所有作者的串联.

Joh*_*Woo 14

由于您正在使用MySQL,请使用GROUP_CONCAT()连接每个组的行.

SELECT  a.Book_ID, 
        a.Title,
        GROUP_CONCAT(c.Name ORDER BY c.Name) Authors
FROM    Book a
        INNER JOIN book_author b
            ON a.Book_ID = b.Book_ID 
        INNER JOIn Author c
            ON b.Author_ID = c.Author_ID
GROUP   BY a.Book_ID, a.Title
Run Code Online (Sandbox Code Playgroud)

OUTPUT

????????????????????????????????????????
? BOOK_ID ? TITLE ?      AUTHORS       ?
????????????????????????????????????????
?       1 ? A     ? Alex,Bob,Bush,John ?
?       2 ? B     ? Alex,Bob           ?
????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)