我有以下SQL选择:
SELECT s.*,
GROUP_CONCAT(CONCAT_WS(':', m.type, m.id, m.filename) SEPARATOR ',') AS multimedia,
GROUP_CONCAT(CONCAT_WS(':', c.id) SEPARATOR ',') AS categories
FROM sections s
LEFT JOIN sections_multimedia sm
ON s.id = sm.section_id
LEFT JOIN multimedia m
ON sm.multimedia_id = m.id
LEFT JOIN sections_categories sc
ON s.id = sc.section_id
LEFT JOIN categories c
ON sc.category_id = c.id
WHERE s.id = s.id
GROUP BY s.id
ORDER BY s.position, s.id ASC;
因此,字段'类别'具有正确的值,即(2,3),但遗憾的是重复多次! (结果是:2,2,2,2,2,2,3,3,3,3,3)
我的选择有什么问题?
感谢您的回复!
答案 0 :(得分:4)
在查找来自不同表的聚合时,您应始终在加入之前进行聚合:
SELECT
s.*,
mul.multimedia,
cat.categories
FROM sections s
LEFT JOIN
(
SELECT
sm.section_id,
GROUP_CONCAT(CONCAT_WS(':', m.type, m.id, m.filename) SEPARATOR ',') AS multimedia
FROM sections_multimedia sm
JOIN multimedia m ON sm.multimedia_id = m.id
GROUP BY sm.section_id
) mul ON s.id = mul.section_id
LEFT JOIN
(
SELECT
sc.section_id,
GROUP_CONCAT(CONCAT_WS(':', c.id) SEPARATOR ',') AS categories
FROM sections_categories sc
JOIN categories c ON sc.category_id = c.id
GROUP BY sc.section_id
) cat ON s.id = cat.section_id;
答案 1 :(得分:3)
您可以使用DISTINCT
:
SELECT s.*,
GROUP_CONCAT(DISTINCT CONCAT_WS(':', m.type, m.id, m.filename) SEPARATOR ',') AS multimedia,
GROUP_CONCAT(DISTINCT CONCAT_WS(':', c.id) SEPARATOR ',') AS categories
这实际上是一种解决方法。您真正的问题是多个连接正在为结果集中的每一行创建值的笛卡尔积。在进行连接之前聚合可能更好,而不是在聚合时删除重复项。