我想列出所有团队,然后计算每个团队在第二个表中出现的次数。有些用户不在第二个表中,因此计数为零。问题是,当我使用count函数时,它只列出第二个表中的用户。我如何计算,如果它们不出现在第二个表中,则列出0?
$query = "SELECT t.id as id, t.t_name as name, t.t_city as city, (count(pd.rs)) as pd FROM #__bl_regions as r, #__bl_teams as t, #__bl_paid as pd WHERE t.id != 0 AND t.id != 1 AND (t.id IN($teams)) AND r.id = ".$t_id." AND pd.rs = 1 AND pd.t_id = ".$t_id." ORDER BY t.t_name";
$db->setQuery($query);
$players = $db->loadObjectList();
尝试左加入
好的,因为我包括3个表格,我相信我必须使用2个查询。同样的事情仍然在发生,只列出有计数的学校。 #__bl_paid是我要计算的表,#__ bl_teams是我要列出的所有表。
$query = "SELECT t.id as id FROM #__bl_regions as r, #__bl_teams as t WHERE t.id != 0 AND t.id != 1 AND (t.id IN($teams)) AND r.id = ".$t_id." ORDER BY t.t_name";
$db->setQuery($query);
$players1 = $db->loadResultArray();
if ($players1){
$players2 = implode(",",$players1);
}else{
$players2 = 0;
}
$query = "SELECT t.id as id, t.t_name as name, t.t_city as city, coalesce((count(pd.rs)),0) as pdc FROM #__bl_paid as pd LEFT JOIN #__bl_teams as t ON pd.t_id = t.id WHERE (t.id IN($players2)) ORDER BY t.t_name";
$db->setQuery($query);
$players = $db->loadObjectList();
答案 0 :(得分:1)
您应该使用LEFT JOIN语句而不是INNER JOIN。
答案 1 :(得分:1)
你需要两件才能得到你想要的东西:
left join
是使用的典型MySQL版本coalesce
inner join
删除另一个表中没有匹配项的行; left join
类似于inner join
,但会保留左表中的所有行,如果右表中没有匹配的行,则会为列提供null。
以下是一个例子:
select column1, coalesce(column2, 0) as `newcolumn2`
from lefttable
left join righttable
on lefttable.something = righttable.something
这将做什么:每当column2
为空时,它将被替换为0.