SELECT categories.*, COUNT(categoryID) AS kritCount
FROM categories AS categories
LEFT JOIN krits ON categories.id = categoryID
WHERE (krits.approved = '1')
GROUP BY categories.id
所以这很有效,只是它没有返回类别中有0个krits的类别。
如果我删除WHERE语句但是我需要WHERE只选择字段批准的krits = 1
答案 0 :(得分:6)
每次从where子句中引用左连接表中的列时(除了测试NULL值),都会强制该连接的行为类似于内连接。相反,将测试移出where子句并使其成为连接条件的一部分。
SELECT categories. * , COUNT(categoryID) AS kritCount
FROM categories AS categories
LEFT JOIN krits
ON categories.id = categoryID
AND krits.approved = '1'
GROUP BY categories.id
答案 1 :(得分:2)
试试这个:
SELECT categories. * , COUNT(categoryID) AS kritCount FROM categories AS categories
LEFT JOIN krits ON categories.id = categoryID
WHERE (krits.approved = '1' OR krits.approved IS NULL)
GROUP BY categories.id
答案 2 :(得分:0)
通过阅读查询,您看起来想要调用类别,并且对于每个类别,您需要针对相应类别计算Krits(已批准),如果没有,则仍需要类别,但显示数为0 ......
试试这个
select
cat.*,
COALESCE( kc.KritCount, 0 ) as KritCount
from
Categories cat
left join ( select k.CategoryID,
count(*) KritCount
from
Krits k
where
k.approved = '1'
group by
k.CategoryID ) kc
on cat.id = kc.CategoryID