mysql count 实现复杂统计解析

mysql的count函数可以计算符合条件的记录条数,比如:

select count(*) from users;

执行结果:
在这里插入图片描述

上面的sql只是将查询到的记录总数输出,count函数本身还可以配合if函数实现更复杂的计数:

select count(if(status = 1, 1, null)) from users

注意,count会将所有非null值计数,所以if里面不符合条件应该返回null。

如果需要按某个字段计算去重后的数量,则需使用 distinct 关键字:

select count(distinct last_name) from users

当需要对1:n的关联查询做统计时,以上简单的count使用方式就不足以实现需求了,比如有以下两个表:

CREATE TABLE `articles` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL COMMENT '标题',
  PRIMARY KEY (`id`)
);

CREATE TABLE `posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `status` tinyint(4) NOT NULL ,
   `article_id` int(10) unsigned NOT NULL
  PRIMARY KEY (`id`)
) 

要在一条sql中查询出所有有帖子(posts)的文章(articles)的数量has_post_cnt、无帖子的文章数量not_post_cnt
首先必定要做连接来关联文章和帖子:

select * from articles left join posts on posts.article_id = articles.id 

一般的思路是连接后再按artiles.id 分组,再在外层对posts.id判断是否等于null:

select count(if(p_id is not null, 1, null)) has_post_cnt, count(if(p_id is null, 1, null)) not_post_cnt from (
	select articles.id a_id, posts.id p_id from articles left join posts on posts.article_id = artiles.id  group by articles.id
) tmp 

但这样的话子查询效率低,考虑不使用子查询的方式实现,首先就必须去掉分组,不然查询结果只能是按分组聚合的结果,出不了所需的计数,首先看这个sql:

select count(if(posts.id is not null, 1, null)) has_post_cnt, 
	count(if(posts.id is null, 1, null)) not_post_cnt
	from articles left join posts on posts.article_id = artiles.id

查询出来的not_post_cnt肯定是对的,因为一条没有帖子的文章和帖子表的连接也就是和null连接,肯定是1:1的,不会有重复记录。
has_post_cnt由于没有对artiles.id做分组,所以是1:n的,这个数是文章的帖子记录数,考虑同一个文章的帖子记录的article_id字段是唯一的,所以使用distinct来做去重处理:

	select count(distinct if(posts.id is not null, posts.article_id, null)) has_post_cnt, 
	count(if(posts.id is null, 1, null)) not_post_cnt
	from articles left join posts on posts.article_id = artiles.id  group by articles.id

这里的关键是count(distinct if(p_id is not null, posts.article_id, null)),先做了去重再做了计数,得到的结果即是有帖子记录的文章数。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲敲代码、落灯花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值