Mysql SQL聚合函数值乘法
在一个查询中,我想对两个不同表中的两个不同列进行计数和分组 问题是,计数返回的数字乘以GROUP_CONCAT中不同项目的数量,在GROUP_CONCAT结果中,每个不同项目乘以计数应返回的数字 以下是查询:Mysql SQL聚合函数值乘法,mysql,sql,group-by,aggregate,multiplication,Mysql,Sql,Group By,Aggregate,Multiplication,在一个查询中,我想对两个不同表中的两个不同列进行计数和分组 问题是,计数返回的数字乘以GROUP_CONCAT中不同项目的数量,在GROUP_CONCAT结果中,每个不同项目乘以计数应返回的数字 以下是查询: SELECT e.id, GROUP_CONCAT(c.id SEPARATOR ',') AS category_ids, COUNT(a.id) AS numberAttenders, e.event_capacity FROM events e LEFT JOIN attendees
SELECT e.id, GROUP_CONCAT(c.id SEPARATOR ',') AS category_ids, COUNT(a.id) AS numberAttenders, e.event_capacity
FROM events e
LEFT JOIN attendees a ON a.event_id=e.id,
categories c,
event_categories ec
WHERE e.id=ec.event_id
AND ec.category_id=c.id
GROUP BY e.id
HAVING numberAttenders < e.event_capacity OR e.event_capacity=0
当我想要这样的东西时:
id 1
category_ids 1,2,1,2
numberAttenders 4
event_capacity 10
id 1
category_ids 1,2
numberAttenders 2
event_capacity 10
我和小组玩了一会儿,但还没有成功的结果。你得到了每个活动的参与者和类别的笛卡尔乘积。最好的解决方案是在执行联接之前聚合表:
SELECT e.id, ec.category_ids, a.NumAttendees, e.event_capacity
FROM events e LEFT JOIN
(SELECT a.event_id, COUNT(*) as NumAttendees
FROM attendees a
GROUP BY a.event_id
) a
ON a.event_id = e.id LEFT JOIN
(SELECT ec.event_id, GROUP_CONCAT(c.id SEPARATOR ',') as category_ids
FROM event_categories ec JOIN
categories c
ON ec.category_id = c.id
GROUP BY ec.event_id
) ec
ON e.id=ec.event_id
HAVING NumAttendees < e.event_capacity OR e.event_capacity = 0;
是一个SQL FIDLE。非常感谢提供一个工作示例,同时我强烈建议您尽最大努力将查询添加到问题本身。我添加了查询,感谢您的评论谢谢您的回答,它正在做我想要的事情。我以前从未想过这个解决方案,所以今天你给了我一个很好的教训。