前言mysql
最近發如今處理Mysql問題時,count()函數頻繁上鏡,經常出如今分組統計的情景下,可是有時候並非使用group by分好組就能夠直接統計了,好比說一個常見的需求,統計每一個班級男生所佔的比例,這種狀況通常會按照班級分組,可是分組內不但要統計班級的人數,還要統計男生的人數,也就是說統計是有條件的,以前確實沒有考慮過怎樣實心,後來查詢了資料,總結在這裏,方便往後查找使用。sql
Mysql中count()函數的通常用法是統計字段非空的記錄數,因此能夠利用這個特色來進行條件統計,注意這裏若是字段是NULL就不會統計,可是false是會被統計到的,記住這一點,咱們接下來看看幾種常見的條件統計寫法。函數
測試環境
Windows 10
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 7
Server version: 5.7.21-log MySQL Community Server (GPL)
Copyright © 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the current input statement.學習
準備工做
新建一個Mysql數據表a,包含id和num兩個字段
mysql> create table a(id int, num int);
Query OK, 0 rows affected (0.04 sec)測試
插入測試數據,爲了看count()函數的效果,咱們插入兩個空數據
mysql> insert into a values (1,100),(2,200),(3,300),(4,300),(8,null),(9,null);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0.net
查詢表a中的數據,與後面的統計作比較blog
mysql> select * from a; | |
---|---|
id | num |
1 | 100 |
2 | 200 |
3 | 300 |
4 | 300 |
8 | NULL |
9 | NULL |
6 rows in set (0.09 sec)get
調用count()函數看效果,若是使用count(*)會查詢出全部的記錄數,但若是使用count(num)發現只有4條數據,num爲NULL的記錄並無統計上input
mysql> select count(*) from a; |
---|
count(*) |
6 |
1 row in set (0.03 sec)it
mysql> select count(num) from a; |
---|
count(num) |
4 |
1 row in set (0.04 sec)
條件統計
count()函數中使用條件表達式加or null來實現,做用就是當條件不知足時,函數變成了count(null)不會統計數量
mysql> select count(num > 200 or null) from a; |
---|
count(num > 200 or null) |
2 |
1 row in set (0.22 sec)
count()函數中使用if表達式來實現,當條件知足是表達式的值爲非空,條件不知足時表達式值爲NULL;
mysql> select count(if(num > 200, 1, null)) from a; |
---|
count(if(num > 200, 1, null)) |
2 |
1 row in set (0.05 sec)
count()函數中使用case when表達式來實現,當條件知足是表達式的結果爲非空,條件不知足時無結果默認爲NULL;
mysql> select count(case when num > 200 then 1 end) from a; |
---|
count(case when num > 200 then 1 end) |
2 |
1 row in set (0.07 sec)
總結
使用count()函數實現條件統計的基礎是對於值爲NULL的記錄不計數,經常使用的有如下三種方式,假設統計num大於200的記錄
select count(num > 200 or null) from a;
select count(if(num > 200, 1, null)) from a
select count(case when num > 200 then 1 end) from a
————————————————
本文僅供本身記錄學習做用,版權歸原做者全部,侵刪
版權聲明:本文爲CSDN博主「AlbertS」的原創文章,遵循CC 4.0 BY-SA
原文連接:https://blog.csdn.net/alberts...