tags:

views:

27

answers:

1

I've got access levels and pages. Pages <=many-to-many=> Levels I need to count how many opened pages does each level has. But the levels doesn't happen to come out if pageCount is 0.

SELECT 
    levels.id,
    levels.name,
    COUNT(pages.id) as pageCount
FROM levels
LEFT JOIN page_levels
    ON levels.id = page_levels.level_id
LEFT JOIN wp_pages
    ON page_levels.page_id = pages.id
WHERE pages.status = 'open'
GROUP BY levels.id

Frustrating. Please tell me what am I missing.

+2  A: 

Move condition to ON().

SELECT 
    levels.id,
    levels.name,
    COUNT(pages.id) as pageCount
FROM levels
LEFT JOIN page_levels
    ON levels.id = page_levels.level_id
LEFT JOIN wp_pages AS pages
    ON page_levels.page_id = pages.id AND pages.status = 'open'
GROUP BY levels.id
Naktibalda
Thanks, works like a charm.
Xobb