我有一个类似下面的模式,我尝试进行查询以从单个项目中获取所有过滤器和所有project_items,以便使用GROUP_CONCAT将结果放在一行中。
[filters] 1 - N [project_filters] N - 1 [项目] 1 - N [project_items]
项目1有3个过滤器(1,2和3)和3个项目(1,2和3),这导致重复值(每个9个),如下所示:
我认为解决方案是以某种方式安排联接,但我无法弄明白。
OBS:带有DISTINCT的GROUP_CONCAT不适合,因为可能会有重复的标题
非常感谢!
答案 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"