數據庫一般用於回答「表中某種類型的數據出現頻率多少?」的問題。例如,你可能想知道你擁有多少隻寵物,或每一個擁有者擁有多少隻寵物,或者你可能想要對你的動物進行各類類型的普查操做。mysql
計算你擁有的動物總數與「pet表中有多少行?」的問題相同。由於每隻寵物有一條記錄,COUNT(*)
計算行數,所以計算動物的查詢以下所示:sql
mysql> SELECT COUNT(*) FROM pet; +----------+ | COUNT(*) | +----------+ | 9 | +----------+
以前,你檢索了擁有寵物的人的姓名,若是你想知道每一個擁有者有多少寵物,你可使用COUNT()
:數據庫
mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner; +--------+----------+ | owner | COUNT(*) | +--------+----------+ | Benny | 2 | | Diane | 2 | | Gwen | 3 | | Harold | 2 | +--------+----------+
上述查詢使用GROUP BY
對每一個owner
的全部記錄進行分組,將COUNT()
與GROUP BY
結合使用在各類分組下描述你的數據很是有用,如下示例顯示了執行動物普查操做的不一樣方法。express
每種動物數量:segmentfault
mysql> SELECT species, COUNT(*) FROM pet GROUP BY species; +---------+----------+ | species | COUNT(*) | +---------+----------+ | bird | 2 | | cat | 2 | | dog | 3 | | hamster | 1 | | snake | 1 | +---------+----------+
每種性別的動物數量:服務器
mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex; +------+----------+ | sex | COUNT(*) | +------+----------+ | NULL | 1 | | f | 4 | | m | 4 | +------+----------+
在此輸出中,NULL
表示性別未知。this
每種物種和性別組合的動物數量:code
mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex; +---------+------+----------+ | species | sex | COUNT(*) | +---------+------+----------+ | bird | NULL | 1 | | bird | f | 1 | | cat | f | 1 | | cat | m | 1 | | dog | f | 1 | | dog | m | 2 | | hamster | f | 1 | | snake | m | 1 | +---------+------+----------+
使用COUNT()
時無需檢索整個表,例如,以前的查詢,只在狗和貓上執行時,以下所示:ci
mysql> SELECT species, sex, COUNT(*) FROM pet WHERE species = 'dog' OR species = 'cat' GROUP BY species, sex; +---------+------+----------+ | species | sex | COUNT(*) | +---------+------+----------+ | cat | f | 1 | | cat | m | 1 | | dog | f | 1 | | dog | m | 2 | +---------+------+----------+
或者,若是你想要每種性別的動物數量僅適用於已知性別的動物:get
mysql> SELECT species, sex, COUNT(*) FROM pet WHERE sex IS NOT NULL GROUP BY species, sex; +---------+------+----------+ | species | sex | COUNT(*) | +---------+------+----------+ | bird | f | 1 | | cat | f | 1 | | cat | m | 1 | | dog | f | 1 | | dog | m | 2 | | hamster | f | 1 | | snake | m | 1 | +---------+------+----------+
若是在COUNT()
值以外指定要選擇的列的名稱,應該存在一個GROUP BY
子句來命名那些相同的列,不然,會發生如下狀況:
若是啓用了ONLY_FULL_GROUP_BY
SQL模式,則會發生錯誤:
mysql> SET sql_mode = 'ONLY_FULL_GROUP_BY'; Query OK, 0 rows affected (0.00 sec) mysql> SELECT owner, COUNT(*) FROM pet; ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'menagerie.pet.owner'; this is incompatible with sql_mode=only_full_group_by
若是未啓用ONLY_FULL_GROUP_BY
,則經過將全部行視爲單個組來處理查詢,但爲每一個命名列選擇的值是不肯定的,服務器能夠自由選擇任何行中的值:
mysql> SET sql_mode = ''; Query OK, 0 rows affected (0.00 sec) mysql> SELECT owner, COUNT(*) FROM pet; +--------+----------+ | owner | COUNT(*) | +--------+----------+ | Harold | 8 | +--------+----------+