SQL中COUNT()函数的用法

本文主要介绍SQL语句中COUNT()函数的用法。

1 概述

1.1 what

COUNT() 函数返回匹配到指定条件的记录行数。

1.2 how

示例数据库表信息如下,下面我们以此表内容为基础,展示COUNT()函数的用法。

SQL中COUNT()函数的用法_第1张图片

语法:SQL COUNT(column_name)
COUNT(column_name) 函数返回指定列的值的数目(NULL 不计入)。例如:

mysql> select COUNT(camp) as num from roles where role_id in (1, 7, 8);
+-----+
| num |
+-----+
|   3 |
+-----+
1 row in set (0.00 sec)

mysql> 
mysql> select COUNT(camp) as num from roles where role_id in (1, 8, 9);
+-----+
| num |
+-----+
|   2 |
+-----+
1 row in set (0.01 sec)

mysql> 


语法:SQL COUNT(*)
COUNT(*) 函数返回符合查询条件的表的记录数。例如:

mysql> select COUNT(*) as num from roles;
+-----+
| num |
+-----+
|   9 |
+-----+
1 row in set (0.00 sec)

mysql> 
mysql> select COUNT(*) as num from roles where role_id in (1, 8, 9);
+-----+
| num |
+-----+
|   3 |
+-----+
1 row in set (0.00 sec)

mysql> 

语法:SQL COUNT(DISTINCT column_name)
COUNT(DISTINCT column_name) 函数返回指定列的不同值的数目。例如:

mysql> select COUNT(camp) as num from roles where role_id in (1, 2, 3);
+-----+
| num |
+-----+
|   3 |
+-----+
1 row in set (0.01 sec)

mysql> 
mysql> select COUNT(DISTINCT camp) as num from roles where role_id in (1, 2, 3);
+-----+
| num |
+-----+
|   2 |
+-----+
1 row in set (0.01 sec)

 

你可能感兴趣的:(数据库)