有一張t3表,表結構和數據如下:
1 mysql> select * from t3; 2 3 +------+------+------+------+ 4 5 | id | num1 | num2 | type | 6 7 +------+------+------+------+ 8 9 | 1 | 123 | 231 | A | 10 11 | 2 | 35 | 13 | A | 12 13 | 3 | 44 | NULL | A | 14 15 | 5 | 89 | 24 | B | 16 17 | 9 | NULL | 31 | B | 18 19 | 10 | 21 | 3 | C | 20 21 | NULL | NULL | NULL | NULL | 22 23 +------+------+------+------+
1、count(*)和count(1)
這種用法下,就是根據查詢語句的條件統計行數,統計出有多少行就返回相應的行數值。例如:
1 mysql> select count(1) from t3; 2 3 +----------+ 4 5 | count(1) | 6 7 +----------+ 8 9 | 7 | 10 11 +----------+ 12 13 1 row in set (0.00 sec) 14 15 16 17 mysql> select count(1) from t3 where num1 is null; 18 19 +----------+ 20 21 | count(1) | 22 23 +----------+ 24 25 | 2 | 26 27 +----------+
2、count(col)
col代表具體的某一列。如果是這種統計方式,那么並不是統計有多少行就返回行數值,而是返回其中非NULL行的行數。例如:
1 mysql> select count(num1) from t3; 2 3 +-------------+ 4 5 | count(num1) | 6 7 +-------------+ 8 9 | 5 | 10 11 +-------------+
3、count(expr)
expr代表表達式。如果現在要求統計t3表中num1列大於num2列的有多少行,那么下面的查詢是錯誤的:
1 mysql> select count(num1>num2) from t3; 2 3 +------------------+ 4 5 | count(num1>num2) | 6 7 +------------------+ 8 9 | 4 | 10 11 +------------------+
實際上,num1大於num2的只有3行(對於值為NULL的不考慮),但是返回的卻是4。實際上這里的“num1>num2”條件並沒有起到過濾作用,這需要按下面的兩種查詢:
1 mysql> select count(num1>num2 or null) count from t3; 2 3 +-------+ 4 5 | count | 6 7 +-------+ 8 9 | 3 | 10 11 +-------+ 12 13 1 row in set (0.00 sec) 14 15 16 17 mysql> select count(case when num1>num2 then 1 end) from t3; 18 19 +---------------------------------------+ 20 21 | count(case when num1>num2 then 1 end) | 22 23 +---------------------------------------+ 24 25 | 3 | 26 27 +---------------------------------------+
也就是說,你想堅持用“num1>num2”做過濾條件,那么必須在后面加上or null才行,或者就是采用case when語句的方式實現過濾。
所以這里有點奇怪,直接用count(num1>num2)根本得不到正確結果,目前也不知道為什么就是不行,估計和count()的實現原理有關。
總結:
count(1)和count(*)是最簡單基本的用法,就是統計待處理的結果集有多少數據行,也包括空行。
除了count(1)和count(*)之外的其它任何用法,count()函數在進行統計時都不會考慮NULL。
count(expr)中的expr可以是col1<col2、col>number還可以是子查詢和case when語句等等;
count(expr)中的expr除了是case when語句,其余的都要加or null才能統計出正確的值,即便是子查詢也要加or null。
測試於MySQL5.7.14,其實以上都是MySQL的語法基礎,但是很長時間沒有涉及到,所以一些細節方面的東西都沒有記住,多走些彎路。。。。
