Mysql 使用Group 和Case When统计数据

项目是基于:thinkcmf的,新的需求是对各栏目的文章数量进行统计

SQl很简单,先根据分类ID进行分组,然后再通过CASE WHEN 再统计不同文章状态数量
SELECT  t.name,t.parent,t.term_id,count(1) as count 

,COUNT( CASE WHEN  p.post_status  = 1 then 1 else null end ) as p1 # 1=已审核
,COUNT( CASE WHEN  p.post_status  = 0 then 0 else null end ) as p0 # 0=未审核
,COUNT( CASE WHEN  p.post_status  = -1 then -1 else null end ) as p_1 #-1=审核未通过

FROM

term_relationships r               
join terms t on r.term_id= t.term_id
join posts p on p.id = r.object_id
                                     
group by t.term_id #以分类ID分组
生成的效果:
 
 
参考:





原文地址:https://www.cnblogs.com/huangtailang/p/5800444.html