日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql 聚合函数 怎么用在条件里_MySql 中聚合函数增加条件表达式的方法

發布時間:2025/3/11 数据库 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql 聚合函数 怎么用在条件里_MySql 中聚合函数增加条件表达式的方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

where 在聚合之前過濾

當一個查詢包含了聚合函數及where條件,像這樣的情況

select max(cid) from t where t.id<999

這時候會先進行過濾,然后再聚合。先過濾出ID《999的記錄,再查找最大的cid返回。

having 在聚合之后過濾

having在分組的時候會使用,對分組結果進行過濾,通常里面包含聚合函數。

SELECT ip,MAX(id) FROM app

GROUP BY ip

HAVING 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) callbackErrorLogs

from

(

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中能不能加條件,找了一下,如下:

select

DATE_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)) callbackErrorLogs

from dxp.dxp_handlermodel

group 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'

好了這篇文章就介紹到這,希望大家以后多多支持聚米學院。

總結

以上是生活随笔為你收集整理的mysql 聚合函数 怎么用在条件里_MySql 中聚合函数增加条件表达式的方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。