语法:SELECT COUNT(*) | COUNT(列名)  FROM 表名 [WHERE 条件语句]


mysql> select * from student_info;
+------+---------+
| age | name |
+------+---------+
| 12 | Lili |
| 27 | Jack |
| 25 | Rose |
| 25 | Ann |
| 26 | Mark |
| 68 | Bill |
| 16 | James |
| 20 | Fred |
| 8 | Gary |
| 22 | Martin |
| 35 | Charles |
| 31 | Joseph |
| 49 | Henry |
| 57 | Mike |
| NULL | Bob |
+------+---------+
15 rows in set (0.00 sec)

mysql>


(1)COUNT(*)

统计表中多少条记录


mysql> SELECT COUNT(*) FROM student_info;
+----------+
| COUNT(*) |
+----------+
| 15 |
+----------+
1 row in set (0.00 sec)

mysql>


(2)COUNT(列名)

统计指定列中有多少条记录,不含值为NULL的


mysql> SELECT COUNT(age) FROM student_info;
+------------+
| COUNT(age) |
+------------+
| 14 |
+------------+
1 row in set (0.00 sec)

mysql>


(3)COUNT(DISTINCT 列名)

统计列中不重复的记录有多少条


mysql> SELECT COUNT(DISTINCT age) FROM student_info;
+---------------------+
| COUNT(DISTINCT age) |
+---------------------+
| 13 |
+---------------------+
1 row in set (0.00 sec)

mysql>


(4)与WHERE连用


# 查找age在(20, 30)之间的记录有多少条
mysql> SELECT COUNT(*) FROM student_info where age >=20 && age <=30;
+----------+
| COUNT(*) |
+----------+
| 6 |
+----------+
1 row in set (0.01 sec)

mysql>