计算左联接组的依据是在结果数据中排除零

时间:2018-07-16 11:52:11

标签: mysql sql

根据此How to include "zero" / "0" results in COUNT aggregate?,我需要离开联接tbl_postad表。

以下是我的查询

此查询显示每个类别中的广告数量。

SELECT c.*, count(a.post_id) as item_count 
FROM tbl_category c 
LEFT JOIN tbl_postad a on a.post_maincategory = c.cat_id 
WHERE c.cat_parent=0 AND c.cat_promote = 0 
AND c.selActive = 'Y' AND a.post_delete_status!='Y' AND a.post_cat_status!='N' 
AND a.post_status='Y' AND a.block=0 AND a.post_expiredate >= '".date("Y-m-d H:i:s")."' 
GROUP BY c.cat_name 
ORDER BY c.cat_sort asc

如果删除与发布相关的查询,则会显示所有类别:

 SELECT c.*, count(a.post_id) as item_count 
 FROM tbl_category c 
 LEFT JOIN tbl_postad a on a.post_maincategory=c.cat_id 
 WHERE c.cat_parent=0 AND c.cat_promote = 0 AND c.selActive = 'Y' 
 GROUP BY c.cat_name 
 ORDER BY c.cat_sort asc

但是,如果我添加与帖子相关的查询,则它将排除帖子计数为零的所有类别。

1 个答案:

答案 0 :(得分:2)

left join中,第二个表上的所有条件都应在on子句中。否则,不匹配项会将left join变成inner join

因此,请尝试以下操作:

select c.*, count(a.post_id) as item_count
from tbl_category c left join
     tbl_postad a
     on a.post_maincategory = c.cat_id and
        a.post_delete_status <> 'Y' and
        a.post_status = 'Y' and
        a.post_cat_status <> 'N' and
        a.block = 0 and
        a.post_expiredate >= '".date("Y-m-d H:i:s")."' 
where c.cat_parent = 0 and
      c.cat_promote = 0 and
      c.selActive = 'Y' ;

注意:您应该学习如何使用参数来传递诸如ate之类的值,而不是笨拙地查询字符串。