左连接查询MySQL

时间:2017-03-08 20:27:08

标签: mysql

我正在查询所有书籍。每本书都有很多作者和许多出版商。 (作者和出版商也可以属于许多书籍。)这是我的表格模式,包含数据:

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)。关于如何防止作者和出版商重复的任何想法?

1 个答案:

答案 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

还有另外两种让我想到的方式,我认为这两种方式都不优雅。

  1. 获取distict作者每个标题发布的子查询,然后使用group_concat
  2. 使用内联选择(在选择中)以获得每本书的不同作者和发布者值列表。