Basic problem is - I'm trying to use a sub-query's count as a variable in my WHERE CASE statement, but it doesn't appear to let me use it. I've got it somewhat working when I put the SELECT COUNT(id)... statement in the WHERE area, but - if I do that, I'll have to include it 3-4 different times instead of just once if I can put it in the SELECT.
Below is a modified example query that explains my problem. It's not the exact query I'm using, but it gives the same error as my much-longer/more complicated query:
Error:
[Err] 1054 - Unknown column 'matched_sections' in 'where clause'
Query:
SELECT
articles.id,
(SELECT COUNT(id) FROM site_areas_site_sections WHERE
site_areas_site_sections.site_area_id = 8) AS matched_sections
FROM
articles
LEFT JOIN
articles_site_sections ON articles_site_sections.article_id = articles.id
LEFT JOIN
site_areas_site_sections ON articles_site_sections.site_section_id =
site_areas_site_sections.site_section_id
WHERE
(CASE
WHEN
matched_sections > 0
THEN
site_sections.id = site_areas_site_sub_sections.site_sub_section_id
END
)
matched_sectioncolumn, your CASE expression seems to have another problem. It references a table that is found nowhere in the FROM clause (site_areas_site_sub_sections).