如果计数0,则不返回Mysql结果

时间:2010-07-07 15:01:32

标签: sql mysql join

我有访问级别和页面。页数< = many-to-many =>水平 我需要计算每个级别有多少打开的页面。但如果pageCount为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

令人沮丧。请告诉我我错过了什么。

1 个答案:

答案 0 :(得分:2)

将条件移至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