使用GROUP_CONCAT重复值而不使用带有多个连接的MySQL查询的DISTINCT

时间:2014-04-09 02:33:35

标签: mysql sql join distinct group-concat

我有一个类似下面的模式,我尝试进行查询以从单个项目中获取所有过滤器和所有project_items,以便使用GROUP_CONCAT将结果放在一行中。

过滤器

  • ID
  • 标题

project_filters

  • ID
  • filters_id
  • projects_id

项目

  • ID
  • 标题

project_items

  • ID
  • 标题
  • projects_id

表格如此连接

[filters] 1 - N [project_filters] N - 1 [项目] 1 - N [project_items]

查询和问题

  • 选择
  • projects.id,
  • projects.title,
  • GROUP_CONCAT(project_items.title)AS items_title,
  • GROUP_CONCAT(filters.title)AS filters_title
  • FROM projects
  • LEFT JOIN project_items ON project_items.projects_id = projects.id
  • LEFT JOIN project_filters ON projects.id = project_filters.projects_id
  • LEFT JOIN过滤器过滤器.id = project_filters.filters_id
  • WHERE projects.id =" 1"

项目1有3个过滤器(1,2和3)和3个项目(1,2和3),这导致重复值(每个9个),如下所示:

  • id = 1
  • title = project 1
  • items_title = title 1,title 2,title 3,title 1,title 2,title 3,title 1,title 2,title 3
  • filters_title =过滤器1,过滤器2,过滤器3,过滤器1,过滤器2,过滤器3,过滤器1,过滤器2,过滤器3

有人能指出我正确的方向吗?我想知道如何使查询返回过滤器和项而不重复。

我认为解决方案是以某种方式安排联接,但我无法弄明白。

OBS:带有DISTINCT的GROUP_CONCAT不适合,因为可能会有重复的标题

非常感谢!

2 个答案:

答案 0 :(得分:1)

好的,通过@cha的答案(感谢队友)和更多的研究,我通过删除两个查询之间的INNER JOIN得到了正确的结果。

SELECT i.id, i.title, i.items_title, f.filters_title FROM
( SELECT
  projects.id,
  projects.title,
  GROUP_CONCAT(project_items.title) AS items_title
  FROM projects
  LEFT JOIN project_items ON project_items.projects_id=projects.id
  WHERE projects.id="1"
  GROUP BY projects.id) AS i,
( SELECT
  projects.id,
  projects.title,
  GROUP_CONCAT(filters.title) AS filters_title
  FROM projects
  LEFT JOIN project_filters ON projects.id=project_filters.projects_id
  LEFT JOIN filters ON filters.id=project_filters.filters_id
  WHERE projects.id="1"
  GROUP BY projects.id) AS f
WHERE i.id=f.id

答案 1 :(得分:0)

为每个GROUP_CONCAT使用子查询:

SELECT i.id, i.title, i.items_title, f.filters_title FROM
( SELECT
  projects.id,
  projects.title,
  GROUP_CONCAT(project_items.title) AS items_title
  FROM projects
  LEFT JOIN project_items ON project_items.projects_id=projects.id
  group by projects.id,
  projects.title) as i
INNER JOIN
( SELECT
  projects.id,
  projects.title,
  GROUP_CONCAT(filters.title) AS filters_title
  FROM projects
  LEFT JOIN project_filters ON projects.id=project_filters.projects_id
  LEFT JOIN filters ON filters.id=project_filters.filters_id
  group by projects.id,
  projects.title) as f
ON i.id = f.id
WHERE i.id="1"