Mysql中使用count加條件統計

2021-09-27 05:03:50 字數 2297 閱讀 3684

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)

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)

條件統計無錫×××醫院

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

mysql中的Count欄位使用

mysql中count 函式的一般用法是統計欄位非空的記錄數,所以可以利用這個特點來進行條件統計,注意這裡如果欄位是null就不會統計,但是false是會被統計到的,記住這一點,我們接下來看看幾種常見的條件統計寫法。測試環境 windows 10 welcome to the mysql monit...

mysql中的count()函式使用

有時候總認為count 會比count 1 或者count column name 慢,事實上是分情況處理。比如 初始化語句 建立一張表並插入資料 create table test2 id bigint primary key,name varchar 24 engine innodb inser...

MySQL優化 1億條資料效率COUNT

最近發現了乙個mysql快速匯入資料方法load data infile,具體參考這個文章。下面用幾條命令來給大家看看,效率結果。簡單說下 1.txt 開始只有10萬資料,後來用vim 新增到了2000萬行,用windows下的編輯器直接卡機的,windows下安裝gvim可以的。資料表型別inno...