加入多个表和GROUP_CONCAT

时间:2018-02-17 18:50:19

标签: mysql sql

我有三个主要表:booksauthorspublishers和两个连接表:authors_on_books& books_on_publishers

我尝试使用以下查询获取所有数据:

select books.*, 
        GROUP_CONCAT(authors.id) as author_id, GROUP_CONCAT(authors.name) as author_name,
        GROUP_CONCAT(publishers.id) as publisher_id, GROUP_CONCAT(publishers.name) as publisher_name

        from books
        join authors_on_books on authors_on_books.book_id = books.id
        join authors on authors_on_books.author_id = authors.id
        join books_on_publishers on books_on_publishers.book_id = books.id
        join publishers on books_on_publishers.publisher_id = publishers.id
        group by books.id

我得到的结果是:

[id] => 1
[title] => Title 1
[description] => This is a book
[year_published] => 1999
[isbn] => 11111111
[author_id] => 1,1,2,2,3,3
[author_name] => author 1,author 1,author 2,author 2,author 3,author 3
[publisher_id] => 1,1,1,1,1,1
[publisher_name] => publisher 1,publisher 1,publisher 1,publisher 1,publisher 1,publisher 1

但理想的结果是:

[id] => 1
[title] => Title 1
[description] => This is a book
[year_published] => 1999
[isbn] => 11111111
[author_id] => 1,2,3
[author_name] => author 1,author 2,author 3
[publisher_id] => 1,2
[publisher_name] => publisher 1,publisher 2

1 个答案:

答案 0 :(得分:3)

您应该在group_concat中使用distinct

  select books.*, 
    GROUP_CONCAT(distinct uthors.id) as author_id, 
    GROUP_CONCAT(distinct authors.name) as author_name,
    GROUP_CONCAT(distinct publishers.id) as publisher_id, 
    GROUP_CONCAT(distinct publishers.name) as publisher_name

    from books
    join authors_on_books on authors_on_books.book_id = books.id
    join authors on authors_on_books.author_id = authors.id
    join books_on_publishers on books_on_publishers.book_id = books.id
    join publishers on books_on_publishers.book_id = publishers.id
    group by books.id

但请记住,group_concat(distinct ...)对性能有一定的影响。

并且根据gordon linoff的建议,您可以使用左连接来确保获取所有书籍

  select books.*, 
    GROUP_CONCAT(distinct uthors.id) as author_id, 
    GROUP_CONCAT(distinct authors.name) as author_name,
    GROUP_CONCAT(distinct publishers.id) as publisher_id, 
    GROUP_CONCAT(distinct publishers.name) as publisher_name

    from books
    left join authors_on_books on authors_on_books.book_id = books.id
    left join authors on authors_on_books.author_id = authors.id
    left join books_on_publishers on books_on_publishers.book_id = books.id
    left join publishers on books_on_publishers.book_id = publishers.id
    group by books.id