统计 status='active' 的记录数:

  • 方法一:直接用where条件

    select count(*) from t where t.status='active';

  • 方法二: 转换为求和,适用于同时统计多个count,group by 的情况

    select sum(if( t.status='active' ,1,0)) from t;

  • 方法三: 利用count()方法, count(1) == 1, count(null) == 0, null 不会被记入count();

    select count( t.status='active' or null) from t;

    • (t.status='active' or null) 当status='active' 为真时(值为1),为假时(值为0)返回null,count(null)不记数,所以可以统计status='active'的个数;