佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > MySql 中聚合函數增加條件表達式的方法

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

熱門標簽:AI電銷 鐵路電話系統(tǒng) 地方門戶網站 呼叫中心市場需求 網站排名優(yōu)化 百度競價排名 Linux服務器 服務外包

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

where 在聚合之前過濾

當一個查詢包含了聚合函數及where條件,像這樣的情況
select max(cid) from t where t.id999
這時候會先進行過濾,然后再聚合。先過濾出ID《999的記錄,再查找最大的cid返回。

having 在聚合之后過濾

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

SELECT ip,MAX(id) FROM app
GROUP BY ip
HAVING MAX(id)>=5 

先分組,再聚合,然后過濾聚合結果大于等于5的結果集

二者的區(qū)別:

where是先執(zhí)行,然后再執(zhí)行聚合函數。having是在聚合函數執(zhí)行完之后再執(zhí)行。

下面是補充

有個需求,某張表,有個狀態(tài)字段(1:成功,2:失敗,類似這樣的),現要用日期分組統(tǒng)計不同狀態(tài)下的數量

先寫了個子查詢

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

執(zhí)行相當慢,想到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')

簡明易懂,且執(zhí)行效率非常高

其它的聚合函數也可以用,如SUM等其他聚合函數

實戰(zhàn)示例:

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 分組查詢和聚合函數
  • MySQL查詢排序與查詢聚合函數用法分析
  • MySQL中聚合函數count的使用和性能優(yōu)化技巧
  • MySQL必備基礎之分組函數 聚合函數 分組查詢詳解

標簽:崇左 湖南 仙桃 蘭州 銅川 黃山 湘潭 衡水

巨人網絡通訊聲明:本文標題《MySql 中聚合函數增加條件表達式的方法》,本文關鍵詞  ;如發(fā)現本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    信丰县| 于都县| 内乡县| 灵璧县| 明光市| 天全县| 齐齐哈尔市| 石狮市| 高密市| 德兴市| 香港| 苏尼特左旗| 德保县| 建昌县| 锡林郭勒盟| 塔城市| 兴安盟| 嘉善县| 瓮安县| 军事| 通海县| 广德县| 宣化县| 珲春市| 洛隆县| 温泉县| 象州县| 昌都县| 榆林市| 青铜峡市| 农安县| 滦平县| 柯坪县| 甘孜县| 赤峰市| 璧山县| 水富县| 忻城县| 大兴区| 万盛区| 纳雍县|