麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 數據庫 > MySQL > 正文

MySql 中聚合函數增加條件表達式的方法

2024-07-25 19:08:32
字體:
來源:轉載
供稿:網友

Mysql 與聚合函數在一起時候where條件和having條件的過濾時機

where 在聚合之前過濾

當一個查詢包含了聚合函數及where條件,像這樣的情況
select max(cid) from t where t.id<999
這時候會先進行過濾,然后再聚合。先過濾出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.logDate=DATE_FORMAT( startTime, '%Y-%m-%d') and executeStatus=1) pendingLogs ,(select count(1) from dxp.dxp_handlermodel where aa.logDate=DATE_FORMAT( startTime, '%Y-%m-%d') and executeStatus=2) successLogs ,(select count(1) from dxp.dxp_handlermodel where aa.logDate=DATE_FORMAT( startTime, '%Y-%m-%d') and executeStatus=3) errorLogs ,(select count(1) from dxp.dxp_handlermodel where aa.logDate=DATE_FORMAT( startTime, '%Y-%m-%d') and executeStatus=4) callbackErrorLogsfrom( select DATE_FORMAT( a.startTime, '%Y-%m-%d') logDate, count(1) totalLogs from dxp.dxp_handlermodel a  group by DATE_FORMAT( a.startTime, '%Y-%m-%d') ) aa

執行相當慢,想到count中能不能加條件,找了一下,如下:

selectDATE_FORMAT( startTime, '%Y-%m-%d') logDate, count(1) totalLogs, count(if(executeStatus=1,true,null)) pendingLogs, count(if(executeStatus=2,true,null)) successLogs, count(if(executeStatus=3,true,null)) errorLogs, count(if(executeStatus=4,true,null)) callbackErrorLogsfrom dxp.dxp_handlermodelgroup by DATE_FORMAT( startTime, '%Y-%m-%d')

簡明易懂,且執行效率非常高

MySql,聚合函數,條件表達式

其它的聚合函數也可以用,如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'

好了這篇文章就介紹到這,希望大家以后多多支持VeVb武林網。


注:相關教程知識閱讀請移步到MYSQL教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黑人日比 | 亚洲性综合网 | 欧美成人免费电影 | 曰批全过程120分钟免费69 | 日韩美香港a一级毛片 | 夜夜看 | 黄色一级毛片免费看 | 国产喷白浆10p | 看片一区 | 欧美成人高清视频 | 色蜜桃av | 欧美一级美国一级 | 一本视频在线观看 | 91毛片网站 | 成品片a免费直接观看 | 午夜视频在线免费播放 | 九九黄色 | 国产黄色网页 | 羞羞漫画无遮挡观看 | 成人黄色短视频在线观看 | 精品一区二区三区四区在线 | 91成人一区 | 8x成人在线电影 | 182tv成人福利视频免费看 | 9191色| 久色porn| 免费国产人成网站 | 一级国产航空美女毛片内谢 | www.射| 亚洲男人一区 | 免费久久久久 | 成人毛片一区 | 国产精品一区二区视频 | 日韩欧美中文字幕视频 | 鲁丝片一区二区三区免费入口 | 九九热免费精品 | 国产自在自线午夜精品视频在 | 91精品国产乱码久久桃 | 末成年女av片一区二区 | 越南一级黄色片 | 毛片久久|