当前位置:   article > 正文

SQL中COUNT()函数介绍_sql count

sql count

本文主要介绍SQL(Structured Query Language)中COUNT()函数的相关知识,同时通过用法示例介绍COUNT()函数的使用方法。

1 概述

1.1 What

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

1.2 How

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

语法格式:COUNT(column_name)

COUNT(column_name)函数返回指定列的值的数目(NULL不计入)。

用法示例如下:

  1. mysql> select COUNT(camp) as num from roles where role_id in (1, 7, 8);
  2. +-----+
  3. | num |
  4. +-----+
  5. | 3 |
  6. +-----+
  7. 1 row in set (0.00 sec)
  8. mysql>
  9. mysql> select COUNT(camp) as num from roles where role_id in (1, 8, 9);
  10. +-----+
  11. | num |
  12. +-----+
  13. | 2 |
  14. +-----+
  15. 1 row in set (0.01 sec)
  16. mysql>

语法:COUNT(*)

COUNT(*)函数返回符合查询条件的表的记录数。

用法示例如下:

  1. mysql> select COUNT(*) as num from roles;
  2. +-----+
  3. | num |
  4. +-----+
  5. | 9 |
  6. +-----+
  7. 1 row in set (0.00 sec)
  8. mysql>
  9. mysql> select COUNT(*) as num from roles where role_id in (1, 8, 9);
  10. +-----+
  11. | num |
  12. +-----+
  13. | 3 |
  14. +-----+
  15. 1 row in set (0.00 sec)
  16. mysql>

语法格式:COUNT(DISTINCT column_name)

COUNT(DISTINCT column_name)函数返回指定列的不同值的数目。

用法示例如下:

  1. mysql> select COUNT(camp) as num from roles where role_id in (1, 2, 3);
  2. +-----+
  3. | num |
  4. +-----+
  5. | 3 |
  6. +-----+
  7. 1 row in set (0.01 sec)
  8. mysql>
  9. mysql> select COUNT(DISTINCT camp) as num from roles where role_id in (1, 2, 3);
  10. +-----+
  11. | num |
  12. +-----+
  13. | 2 |
  14. +-----+
  15. 1 row in set (0.01 sec)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/929509
推荐阅读
相关标签
  

闽ICP备14008679号