编写网站的软件,网站制作经费预算,网站设计软件手机版,微博通 for wordpressMysql 与聚合函数在一起时候where条件和having条件的过滤时机where 在聚合之前过滤当一个查询包含了聚合函数及where条件#xff0c;像这样的情况select max(cid) from t where t.id999这时候会先进行过滤#xff0c;然后再聚合。先过滤出ID《999的记录#xff0c;再查找…Mysql 与聚合函数在一起时候where条件和having条件的过滤时机where 在聚合之前过滤当一个查询包含了聚合函数及where条件像这样的情况select max(cid) from t where t.id999这时候会先进行过滤然后再聚合。先过滤出ID《999的记录再查找最大的cid返回。having 在聚合之后过滤having在分组的时候会使用对分组结果进行过滤通常里面包含聚合函数。SELECT ip,MAX(id) FROM appGROUP BY ipHAVING MAX(id)5先分组再聚合然后过滤聚合结果大于等于5的结果集二者的区别where是先执行然后再执行聚合函数。having是在聚合函数执行完之后再执行。下面是补充有个需求某张表有个状态字段(1成功2失败类似这样的)现要用日期分组统计不同状态下的数量先写了个子查询select aa.logDate,aa.totalLogs,(select count(1) from dxp.dxp_handlermodel where aa.logDateDATE_FORMAT( startTime, %Y-%m-%d) and executeStatus1) pendingLogs,(select count(1) from dxp.dxp_handlermodel where aa.logDateDATE_FORMAT( startTime, %Y-%m-%d) and executeStatus2) successLogs,(select count(1) from dxp.dxp_handlermodel where aa.logDateDATE_FORMAT( startTime, %Y-%m-%d) and executeStatus3) errorLogs,(select count(1) from dxp.dxp_handlermodel where aa.logDateDATE_FORMAT( startTime, %Y-%m-%d) and executeStatus4) callbackErrorLogsfrom(selectDATE_FORMAT( a.startTime, %Y-%m-%d) logDate,count(1) totalLogsfrom dxp.dxp_handlermodel agroup by DATE_FORMAT( a.startTime, %Y-%m-%d)) aa执行相当慢想到count中能不能加条件找了一下如下selectDATE_FORMAT( startTime, %Y-%m-%d) logDate,count(1) totalLogs,count(if(executeStatus1,true,null)) pendingLogs,count(if(executeStatus2,true,null)) successLogs,count(if(executeStatus3,true,null)) errorLogs,count(if(executeStatus4,true,null)) callbackErrorLogsfrom dxp.dxp_handlermodelgroup by DATE_FORMAT( startTime, %Y-%m-%d)简明易懂且执行效率非常高其它的聚合函数也可以用如SUM等其他聚合函数实战示例select count(if(create_date 2017-01-01 and host_profile_id 9294d2bf-f457-4fe5-9a36-e5f832310dc2,true,null)) from profile_visit_log-- 等同于select count(if(create_date 2017-01-01,true,null)) count from profile_visit_log where host_profile_id 9294d2bf-f457-4fe5-9a36-e5f832310dc2好了这篇文章就介绍到这希望大家以后多多支持聚米学院。