I’m experiencing a problem with a MySQL nested subquery where the error indicates that a column cannot be found. This happened after I tried to sum the results of two separate queries using UNION ALL within my subquery.
SELECT DISTINCT category.ID,
category.Name,
department.Name as Dept,
(
SELECT SUM(total_count)
FROM (
( SELECT COUNT(event1.ID) as total_count
FROM event_list event1
JOIN event_category_links ecl1 ON (event1.ID = ecl1.EventID)
JOIN event_location_links ell1 ON (event1.ID = ell1.EventID)
JOIN location_table loc1 ON (ell1.LocationID = loc1.ID)
WHERE ecl1.CategoryID = category.ID
AND department.ID = loc1.RegionID
AND event1.EventDate >= CURRENT_DATE()
AND event1.GroupID IS NULL GROUP BY event.ID
)
UNION ALL
( SELECT COUNT(DISTINCT event1.GroupID) as total_count
FROM event_list event1
JOIN event_category_links ecl1 ON (event1.ID = ecl1.EventID)
JOIN event_location_links ell1 ON (event1.ID = ell1.EventID)
JOIN location_table loc1 ON (ell1.LocationID = loc1.ID)
WHERE ecl1.CategoryID = category.ID
AND department.ID = loc1.RegionID
AND event1.EventDate >= CURRENT_DATE()
AND event1.GroupID IS NOT NULL GROUP BY event.GroupID
)
) as summary
) as EventCount,
loc.Name as City
FROM event_category_links ec
JOIN categories category ON (ec.CategoryID = category.ID)
JOIN event_list event ON (event.ID = ec.EventID)
JOIN event_location_links ell ON (event.ID = ell.EventID)
JOIN location_table loc ON (ell.LocationID = loc.ID)
JOIN department_table department ON (loc.RegionID = department.ID)
WHERE department.ID = '50'
AND event.EventDate >= CURRENT_DATE()
AND event.IsActive >= 1
AND event.IsApproved != 2
AND loc.Country = 'US'
The error message states that it could not locate the column that’s referenced from the outer query. When I had a single query before including the UNION ALL, everything functioned correctly. However, with the new SUM and UNION ALL approach, MySQL raises an unknown column error. Can someone advise on how to resolve the column scope issue?