mysql中的Count字段使用

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

查詢表a中的數據,與後面的統計做比較

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)

調用count()函數看效果,如果使用count(*)會查詢出所有的記錄數,但如果使用count(num)發現只有4條數據,num爲NULL的記錄並沒有統計上

mysql> select count(*) from a;

| count(*) |

| 6 |

1 row in set (0.03 sec)

mysql> select count(num) from a;

| count(num) |

| 4 |

1 row in set (0.04 sec)

條件統計無錫×××醫院 https://yyk.familydoctor.com.cn/20612/

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章