[英]Repeated values with GROUP_CONCAT without using DISTINCT on MySQL query with multiple joins
I have a schema like the one below and I'm trying to make a query to get all filters and all project_items from a single project, so that the results are just in one line by using GROUP_CONCAT. 我有一个类似于下面的模式,我试图进行查询以从单个项目中获取所有过滤器和所有project_items,以便通过使用GROUP_CONCAT将结果放在一行中。
[filters] 1--N [project_filters] N--1 [projects] 1--N [project_items] [过滤器] 1--N [项目过滤器] N--1 [项目] 1--N [项目_物品]
Project 1 has 3 filters (1, 2 and 3) and 3 items (1, 2 and 3), which is resulting in repeated values (9 for each), like this: 项目1具有3个过滤器(1、2和3)和3个项目(1、2和3),这导致重复的值(每个为9),如下所示:
I think the solution is to arrange the joins somehow, but I can't figure it out. 我认为解决方案是以某种方式安排联接,但我不知道。
OBS: GROUP_CONCAT with DISTINCT doesn't fit because there might be repeating titles OBS:带有DISTINCT的GROUP_CONCAT不适合,因为可能会有重复的标题
Thank you very much! 非常感谢你!
All right, with @cha's answer (thanks mate) and some more research, I got the right result by removing the INNER JOIN between the two queries. 好的,有了@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
Use subqueries for each of GROUP_CONCATs: 对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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.