实例1:
create table test (id int);
insert into test values(1),(2),(3),(4),(5),(6),(7),(8);
例如:查询id大于4和id=1的统计
一般写法
select count(case when id>4 then id end),count(case when id=1
then id end ) from test;
非主流写法:
select count(id>4 or null),count(id=1 or null) from
test;
--------------------------------------------------------------------
以上测试通过
实例2:
在mysql的count查询中加入条件,在mysql的count查询中加入条件,在mysql的count查询中加入条件,在mysql的count查询中加入条件,
select
count(pp_id),count(if(view_type='2',true,null
)),count(if(bounce_type='1',true,null )),count(DISTINCT
program_id),SUM(play_interval) from v_calculate_play where
app_id=app_id
实例3:
mysql count(*)
统计查询,如果带条件都是很慢的,如果不带条件就很快
count(*)是在没有where条件下很快如果大多都一样,思路反向测试下
方法一:select (select count(*) from alltable)-count(*) from alltable
where x <> 1;
或者使用sum
方法二:select sum(if(x=1,1,0)) from alltable ;
还可以使用count不统计null的方式实现
方法三:select count(x=1 or null) from alltable ;
因我这里没环境,你可以测试下这三种方式的效率
自我总结:
1、count函数对于null会计算为0,没有数据是结果是0;
sum函数对于null不会计算,没有数据时结果是null
在调用sum函数时,要加ifnull()函数包围,给缺省值
2、count函数和sum函数以及其他函数,都可以统计带条件的查询项
3、count函数和sum函数,统计条件是,一般如下面3种:
1) case when
2) if else
3) 直接放置boolean型变量
4、关于类型的转换,如果统计项中的表达式没有boolean型,是不会转换成boolean型的
如果有了 or 或 and 等条件,0会转换为false,非0会转化为true
扩展引申(count中条件和sum中条件的区别):
1、select count(true) ,count(false),count(null)
1,1,0
2、select sum(true),sum(false),sum(null)
1,0,null
3、select count(true or null ) ,count(false or null)
1,0
4、select sum(true or null ) ,sum(false or null)
1,null
可见:对于情景1:统计符合条件的记录数,count和sum都可以达到,
分别采用count(条件 or null) 和 sum(条件
and true)或ifnull(sum(条件),0)
可以达到条件满足时,统计,不满足是,不统计,为空时为0的结果
直接采用count(条件),及时条件为false也会统计
直接采用sum(条件),当没有记录的时候,会返回null
对于情景2:统计符合条件的字段的和,count达不到,sum可以达到,
采用if/else :例如下面
SUM(IF(eor2.resname IN
('sms','unicomSms','mobileSms','telecomSms') AND e.create_time >
DATE_SUB(CURRENT_DATE(),INTERVAL 1
DAY),eor2.amount,0))
扩展示例1:
SET @lt_reg = '^1((3[012]|45|5[56]|76|8[56])[0-9]{8}|(709)[0-9]{7})$';
SELECT
b.org_id
,COUNT(1) col6
,COUNT(b.mobile RLIKE @lt_reg || NULL) col7
,COUNT(b.registered OR NULL) col8
,COUNT(b.mobile RLIKE @lt_reg AND b.registered OR NULL) col9
,CONCAT(ROUND(COUNT(b.registered OR NULL)/COUNT(1)*100,2),'%')
col10
FROM
org_member_t b
WHERE
b.status=0
GROUP BY
b.org_id
扩展示例2:
SELECT org.id
,SUM(IF(eor2.resname = 'msg',eor2.amount,0)) col12
,SUM(IF(eor2.resname IN
('sms','unicomSms','mobileSms','telecomSms'),eor2.amount,0))
col13
,SUM(IF(eor2.resname = 'msg' AND e.create_time >
DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY),eor2.amount,0)) col15
,SUM(IF(eor2.resname IN
('sms','unicomSms','mobileSms','telecomSms') AND e.create_time >
DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY),eor2.amount,0)) col16
FROM event_t
e, event_orig_res_t eor2, account_t a,
org_entity_t
org
WHERE e.id =
eor2.event_id
AND
e.account_id = a.id
AND a.login
= CONCAT('Org-', org.id)
AND
org.status=0
GROUP BY
org.id