主頁(yè) > 知識(shí)庫(kù) > MySql 中聚合函數(shù)增加條件表達(dá)式的方法

MySql 中聚合函數(shù)增加條件表達(dá)式的方法

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

Mysql 與聚合函數(shù)在一起時(shí)候where條件和having條件的過(guò)濾時(shí)機(jī)

where 在聚合之前過(guò)濾

當(dāng)一個(gè)查詢包含了聚合函數(shù)及where條件,像這樣的情況
select max(cid) from t where t.id999
這時(shí)候會(huì)先進(jìn)行過(guò)濾,然后再聚合。先過(guò)濾出ID《999的記錄,再查找最大的cid返回。

having 在聚合之后過(guò)濾

having在分組的時(shí)候會(huì)使用,對(duì)分組結(jié)果進(jìn)行過(guò)濾,通常里面包含聚合函數(shù)。

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

先分組,再聚合,然后過(guò)濾聚合結(jié)果大于等于5的結(jié)果集

二者的區(qū)別:

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

下面是補(bǔ)充

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

先寫了個(gè)子查詢

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í)行相當(dāng)慢,想到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')

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

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

實(shí)戰(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 聚合函數(shù)排序
  • MySQL 分組查詢和聚合函數(shù)
  • MySQL查詢排序與查詢聚合函數(shù)用法分析
  • MySQL中聚合函數(shù)count的使用和性能優(yōu)化技巧
  • MySQL必備基礎(chǔ)之分組函數(shù) 聚合函數(shù) 分組查詢?cè)斀?/li>

標(biāo)簽:崇左 湖南 仙桃 蘭州 銅川 黃山 湘潭 衡水

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

    • 400-1100-266