我想列出所有團隊,然後統計每個團隊在第二張表中出現的次數。有些用戶不在第二個表中,因此計數爲零。問題是當我使用計數功能時,它只列出第二個表中的用戶。我如何計數,並列出0,如果他們不出現在第二個表中?MySQL:在第二張表中統計匹配的行
$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();
現在嘗試這個權利.... – user1232073 2012-02-27 18:27:11
好了,因爲我被替換包括3個表格,我相信我必須使用2個查詢。同樣的事情仍在發生,只列出了有數的學校。 – user1232073 2012-02-27 19:33:55