我有访问级别和页面。页数< = 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
令人沮丧。请告诉我我错过了什么。
答案 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