我正在尝试在找不到该特定ID的记录时显示零。
图像是我想要实现的目标。现在我只得到他找到至少一条记录的行(所以3,4和5)。
有人可以告诉我我做错了什么。这是我的尝试(许多之一):
SELECT statusses.statusses_namenl,
IFNULL(COUNT(projectrecipes.fk_projectrecipes_projectid),0) AS CntRows
FROM recipes
RIGHT JOIN projectrecipes
ON projectrecipes.fk_projectrecipes_recipeid = recipes.id
LEFT JOIN statusses
ON recipes.fk_recipe_status = statusses.id
WHERE projectrecipes.fk_projectrecipes_projectid = 213
GROUP BY recipes.fk_recipe_status
这是我得到的结果:
答案 0 :(得分:0)
我认为你不需要使用CASE,也可以使用RIGHT join,所以如果Join中没有匹配,那么结果也会出现。尝试下面它应该工作。
SELECT recipes.fk_recipe_status, COUNT(projectrecipes.fk_projectrecipes_projectid)
FROM projectrecipes
RIGHT JOIN recipes
ON projectrecipes.fk_projectrecipes_recipeid = recipes.id
WHERE projectrecipes.fk_projectrecipes_projectid = 213
GROUP BY recipes.fk_recipe_status
答案 1 :(得分:0)
试试这个:
SELECT recipes.fk_recipe_status,
IFNULL(COUNT(projectrecipes.fk_projectrecipes_projectid),0) AS CntRows
FROM projectrecipes
RIGHT JOIN recipes
ON projectrecipes.fk_projectrecipes_recipeid = recipes.id
WHERE projectrecipes.fk_projectrecipes_projectid = 213
GROUP BY recipes.fk_recipe_status
答案 2 :(得分:0)
SELECT recipes.fk_recipe_status,
COALESCE(COUNT(projectrecipes.fk_projectrecipes_projectid),0) AS CntRows
FROM projectrecipes
RIGHT JOIN recipes
ON projectrecipes.fk_projectrecipes_recipeid = recipes.id
WHERE projectrecipes.fk_projectrecipes_projectid = 213
GROUP BY recipes.fk_recipe_status
答案 3 :(得分:0)
我认为,加入和应该改变的地方。所以我接受了保罗的答案并修改:
SELECT recipes.fk_recipe_status, COUNT(projectrecipes.fk_projectrecipes_projectid)
转动JOIN中的表格
FROM recipes
LEFT JOIN projectrecipes
ON projectrecipes.fk_projectrecipes_recipeid = recipes.id
GROUP BY recipes.fk_recipe_status
添加一个而不是在哪里
HAVING projectrecipes.fk_projectrecipes_projectid = 213
OR COUNT(projectrecipes.fk_projectrecipes_projectid) = 0
对于某些配方(示例中为1和2),找不到projectrecipes中的数据。因此,如果您首先从projectrecipes中选择,则不会从配方中获取所有数据。
由于projectrecipes可能不包含结果中的数据,projectrecipes.fk_projectrecipes_projectid = 213将始终为false。如果没有找到数据,请检查是否找不到数据,例如count = 0。
答案 4 :(得分:0)
您希望每个状态有一行,因此请从状态中选择。然后,您希望从每个状态的食谱和项目配方中计算记录,因此外部连接它们。将您的条件放在ON子句中,而不是在WHERE子句中,因为当没有匹配的记录时,fk_projectrecipes_projectid将为NULL。 (通过在where子句中使用外部联接列,将外部联接转换为内部联接。)
select s.statusses_namenl, count(*)
from statusses
left join recipes r on r.fk_recipe_status = s.id
left join projectrecipes pr on pr.fk_projectrecipes_recipeid = r.id and pr.fk_projectrecipes_projectid = 213
group by s.statusses_namenl;