SQL聚合函数值乘法
SQL aggregate functions value multiplication
在单个查询中,我想对来自两个不同表的两个不同列进行 COUNT
和 GROUP_CONCAT
。
问题是 COUNT
返回的数字乘以 GROUP_CONCAT
中不同项目的数量,而在 GROUP_CONCAT
结果中,每个不同项目都乘以COUNT 应该返回的数字。
这里是查询:
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
这是一个 SQL Fiddle 所以这个更 clear/testable。
结果看起来像这样:
id 1
category_ids 1,2,1,2
numberAttenders 4
event_capacity 10
当我想要这样的东西时:
id 1
category_ids 1,2
numberAttenders 2
event_capacity 10
我玩了一点 GROUP BY
但还没有成功。
您将获得每个活动的参加者和类别的笛卡尔积。最好的解决方案是在 之前聚合表 进行连接:
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;
Here 是 SQL Fiddle.
在单个查询中,我想对来自两个不同表的两个不同列进行 COUNT
和 GROUP_CONCAT
。
问题是 COUNT
返回的数字乘以 GROUP_CONCAT
中不同项目的数量,而在 GROUP_CONCAT
结果中,每个不同项目都乘以COUNT 应该返回的数字。
这里是查询:
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
这是一个 SQL Fiddle 所以这个更 clear/testable。
结果看起来像这样:
id 1
category_ids 1,2,1,2
numberAttenders 4
event_capacity 10
当我想要这样的东西时:
id 1
category_ids 1,2
numberAttenders 2
event_capacity 10
我玩了一点 GROUP BY
但还没有成功。
您将获得每个活动的参加者和类别的笛卡尔积。最好的解决方案是在 之前聚合表 进行连接:
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;
Here 是 SQL Fiddle.