千家信息网

Mysql中使用count加条件统计

发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,Mysql中count()函数的一般用法是统计字段非空的记录数,所以可以利用这个特点来进行条件统计,注意这里如果字段是NULL就不会统计,但是false是会被统计到的,记住这一点,我们接下来看看几种常
千家信息网最后更新 2026年11月02日Mysql中使用count加条件统计

  Mysql中count()函数的一般用法是统计字段非空的记录数,所以可以利用这个特点来进行条件统计,注意这里如果字段是NULL就不会统计,但是false是会被统计到的,记住这一点,我们接下来看看几种常见的条件统计写法。

  测试环境

  Windows 10

  Welcome to the MySQL monitor. Commands end with ; or \g.

  Your MySQL connection id is 7

  Server version: 5.7.21-log MySQL Community Server (GPL)

  Copyright © 2000, 2018, Oracle and/or its affiliates. All rights reserved.

  Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

  Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

  准备工作

  新建一个Mysql数据表a,包含id和num两个字段

  mysql> create table a(id int, num int);

  Query OK, 0 rows affected (0.04 sec)

  插入测试数据,为了看count()函数的效果,我们插入两个空数据

  mysql> insert into a values (1,100),(2,200),(3,300),(4,300),(8,null),(9,null);

  Query OK, 6 rows affected (0.01 sec)

  Records: 6 Duplicates: 0 Warnings: 0

  查询表a中的数据,与后面的统计做比较

  mysql> select * from a;

  | id | num |

  | 1 | 100 |

  | 2 | 200 |

  | 3 | 300 |

  | 4 | 300 |

  | 8 | NULL |

  | 9 | NULL |

  6 rows in set (0.09 sec)

  调用count()函数看效果,如果使用count(*)会查询出所有的记录数,但如果使用count(num)发现只有4条数据,num为NULL的记录并没有统计上

  mysql> select count(*) from a;

  | count(*) |

  | 6 |

  1 row in set (0.03 sec)

  mysql> select count(num) from a;

  | count(num) |

  | 4 |

  1 row in set (0.04 sec)

  条件统计无锡×××医院 https://yyk.familydoctor.com.cn/20612/

  count()函数中使用条件表达式加or null来实现,作用就是当条件不满足时,函数变成了count(null)不会统计数量

  mysql> select count(num > 200 or null) from a;

  | count(num > 200 or null) |

  | 2 |

  1 row in set (0.22 sec)

  count()函数中使用if表达式来实现,当条件满足是表达式的值为非空,条件不满足时表达式值为NULL;

  mysql> select count(if(num > 200, 1, null)) from a;

  | count(if(num > 200, 1, null)) |

  | 2 |

  1 row in set (0.05 sec)

  count()函数中使用case when表达式来实现,当条件满足是表达式的结果为非空,条件不满足时无结果默认为NULL;

  mysql> select count(case when num > 200 then 1 end) from a;

  | count(case when num > 200 then 1 end) |

  | 2 |

  1 row in set (0.07 sec)

  总结

  使用count()函数实现条件统计的基础是对于值为NULL的记录不计数,常用的有以下三种方式,假设统计num大于200的记录

  select count(num > 200 or null) from a;

  select count(if(num > 200, 1, null)) from a

  select count(case when num > 200 then 1 end) from a


统计 条件 函数 表达式 数据 字段 两个 效果 结果 查询 测试 接下来 作用 写法 医院 只有 基础 就是 常用 常见 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 什么是科技互联网 中智农互联网科技 互联网科技与金融科技 万易互联网科技 齐家互联网科技 奇酷互联网络科技 海南科技产业互联网平台 博兴的互联网电子科技公司 阿大互联网科技有限公司 中科明德北京互联网科技 国大互联网教育科技有限公司薪资 富国互联网金融科技混合基金 富国互联网科技002692 新氧科技和美国互联网有关系吗 昆明中奇联合互联网科技 唯美互联网科技 米泉互联网科技专业怎么样 唐山双旺合互联网科技产业园 广西泛欧互联网科技有限公司 陕西彩京云互联网科技有限公司 华服互联网科技怎么样 港股互联网科技股 北京禾田雨橡互联网科技 佰商互联网科技有限公司 互联网和高科技公司 银川新华互联网科技职业技术培训学校图片 福建科技产业互联网发展 互联网公司高科技产品 广州百诚互联网科技有限公司官网 九思连强互联网电子科技有限公司
0