CREATE TABLE book (`id` int, `name` varchar(55));
CREATE TABLE author (`id` int, `name` varchar(55));
CREATE TABLE publisher (`id` int, `name` varchar(55));
CREATE TABLE book_author (`book_id` int, `author_id` int);
CREATE TABLE book_publisher (`book_id` int, `publisher_id` int);
这是我的问题:
SELECT book.title
, GROUP_CONCAT(author.id SEPARATOR ';') AS authors
, GROUP_CONCAT(publisher.id SEPARATOR ';') AS publishers
FROM book
LEFT JOIN book_author ON book.id = book_author.book_id
LEFT JOIN author ON book_author.author_id = author.id
LEFT JOIN book_publisher ON book.id = book_publisher.book_id
LEFT JOIN publisher ON book_publisher.publisher_id = publisher.id
GROUP BY book.id
包含1位作者和1位发布者的图书将两次返回作者ID。一本有5位作者和1位出版商的书将两次返回作者ID(如下:1,1,2,2,3,3,4,4,5,5)。关于如何防止作者和出版商重复的任何想法?
答案 0 :(得分:0)
在group_concat(
之后和字段之前添加单词distinct。
GROUP_CONCAT(distinct author.id SEPARATOR ';') AS authors
, GROUP_CONCAT(distinct publisher.id SEPARATOR ';') AS publishers
这是GROUP_CONCAT函数的documented feature:
完整:
SELECT book.title
, GROUP_CONCAT(Distinct author.id SEPARATOR ';') AS authors
, GROUP_CONCAT(Distinct publisher.id SEPARATOR ';') AS publishers
FROM book
LEFT JOIN book_author ON book.id = book_author.book_id
LEFT JOIN author ON book_author.author_id = author.id
LEFT JOIN book_publisher ON book.id = book_publisher.book_id
LEFT JOIN publisher ON book_publisher.publisher_id = publisher.id
GROUP BY book.id
还有另外两种让我想到的方式,我认为这两种方式都不优雅。