【问题标题】:Duplicate Data in Left Join Query MySQL左连接查询MySQL中的重复数据
【发布时间】:2017-03-08 20:27:07
【问题描述】:

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

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

【问题讨论】:

  • 呃,不会的。但是一本有两个出版商的书会

标签: mysql


【解决方案1】:

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. 一个子查询,获取每个标题的不同作者的发布,然后使用 group_concat
  2. 使用内联选择(在选择中)仅获取每本书的不同作者和出版商值列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多