SQL: 3 tables (book, author, book_author)

I have 3 tables in my MySQL database that have the following structures:

Table of books:

     BOOK
---------------
book_id | title
---------------
   1    |   A
   2    |   B

Authors table:

     AUTHOR
----------------
author_id | name
----------------
     1    | John
     2    | Bush
     3    | Alex
     4    | Bob

And then I have a join table that establishes a many-to-many relationship between the book’s table and the author, which means that the book can be written by many authors (co-authors), and the author can have many books that he wrote.

    BOOK_AUTHOR
--------------------
book_id |  author_id
--------------------
   1    |     1
   1    |     2
   1    |     3
   1    |     4
   2    |     3
   2    |     4

Is it possible using SQL or MySQL to force the DBMS to output something like this:

 book_id |  title  |       authors
------------------------------------------
    1    |    A    | John, Bush, Alex, Bob
    2    |    B    | Alex, Bob

The line of authors at the output is a concatenation of all authors associated with a particular book.

+5
source share
2 answers

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

╔═════════╦═══════╦════════════════════╗
║ BOOK_ID ║ TITLE ║      AUTHORS       ║
╠═════════╬═══════╬════════════════════╣
║       1 ║ A     ║ Alex,Bob,Bush,John ║
║       2 ║ B     ║ Alex,Bob           ║
╚═════════╩═══════╩════════════════════╝
+11

, .

, Oracle folks. bcz Sql Oracle , ... ..

SELECT  book.BOOK_ID, book.BOOK_TITLE, 
listagg (CONCAT(CONCAT(author.AUTHOR_FIRSTNAME, ' '),author.AUTHOR_LASTNAME), ',') 
WITHIN GROUP 
(ORDER BY author.AUTHOR_FIRSTNAME) FirstName
FROM    Books book
        INNER JOIN authorbooks ab
            ON ab.BOOKS_ID = book.BOOK_ID
        INNER JOIN Authors author
            ON ab.Author_id = author.Author_ID
GROUP BY book.BOOK_ID, book.BOOK_TITLE;

, .

+1

All Articles