SELECT events.id, events.name, events.code, event_statuses.name as event_status_name
, regions.name as event_region_name, event_locations.name as event_location_name
, events.date_1, events.date_2
, count(r.id) as regs
FROM events
INNER JOIN event_locations ON event_locations.id = events.event_location_id
INNER JOIN event_statuses ON event_statuses.id = events.event_status_id
LEFT OUTER JOIN regions ON regions.id = events.region_id
LEFT OUTER JOIN registrations as r ON events.id = r.event_id and r.registration_status_id = 4
WHERE 1 GROUP BY events.id ORDER BY date_1 DESC LIMIT 0, 50
如您所见,我的查询具有聚合函数,它在按事件分组的注册上执行。
但是,我希望在此查询中有另一个GROUP BY
,这个没有任何其他聚合函数。这里的要点是我希望按区域对事件列表进行分组 - 现在对它们排序的内容很重要。如果它们按regs
排序 - 我会将来自波士顿的所有事件聚集在一起,然后按照regs进行排序。因此需要另一个Group By。这就是我提出的,但这也不起作用:
SELECT events.id, events.name, events.code, event_statuses.name as event_status_name
,regions.name as event_region_name, event_locations.name as event_location_name
, events.date_1, events.date_2, r.regs
FROM events
INNER JOIN event_locations ON event_locations.id = events.event_location_id
INNER JOIN event_statuses ON event_statuses.id = events.event_status_id
LEFT OUTER JOIN regions ON regions.id = events.region_id
LEFT OUTER JOIN
(Select event_id, count(id) as regs
from registrations where registration_status_id = 4
group by event_id) r on events.id = r.event_id
WHERE 1 GROUP BY events.region_id, events.id ORDER BY date_1 DESC LIMIT 0, 50
我仍然不能按地区将它们分组。
答案 0 :(得分:1)
我希望按区域对事件列表进行分组 - 现在对它们排序的内容很重要。如果它们按照regs排序 - 我会将来自波士顿的所有事件聚集在一起,然后按照regs进行排序。
你想要ORDER BY,而不是GROUP BY。您可以在ORDER BY子句中的所有其他字段之前添加要“聚集在一起”的字段。
ORDER BY region_id, regs
答案 1 :(得分:0)
这是修改后的版本
SELECT
events.id,
events.region_id,
events.name,
events.code,
event_statuses.name as event_status_name,
regions.name as event_region_name,
event_locations.name as event_location_name,
events.date_1,
events.date_2,
r.regs
FROM events
INNER JOIN event_locations
ON event_locations.id = events.event_location_id
INNER JOIN event_statuses
ON event_statuses.id = events.event_status_id
LEFT OUTER JOIN regions
ON regions.id = events.region_id
LEFT OUTER JOIN (Select
event_id,
count(id) as regs
from registrations
where registration_status_id = 4
group by event_id) r
on events.id = r.event_id
WHERE 1
GROUP BY events.region_id, events.id
ORDER BY date_1 DESC
LIMIT 0, 50
试试这个我只选择了events.region_id列
答案 2 :(得分:0)
如果你想“聚集在一起”,那么听起来就像你想要使用并汇总为regs。
SELECT
events.id,
events.name,
events.code,
event_statuses.name as event_status_name,
regions.name as event_region_name,
event_locations.name as event_location_name,
events.date_1,
events.date_2,
SUM(r.regs) AS regs
....
GROUP BY events.region_id, events.id ORDER BY date_1 DESC LIMIT 0, 50