count(distinct xxx) 和 group by 做去重隐藏的坑

本文通过示例揭示了在MySQL中,使用`count(distinct xxx)`与`group by`进行数据去重时可能出现的不同结果。当涉及NULL值时,`count(distinct xxx)`会自动过滤NULL,而`group by`则不会,导致两者得出的统计结果不一致。
摘要由CSDN通过智能技术生成

不说废话,直接上代码。

以下查询是基于mysql自带的country,city,countrylanguage三个样例表做的:

select count(*) from country
union all 
SELECT count(distinct Code, Name, Continent, Region, SurfaceArea, IndepYear, Population, LifeExpectancy, GNP, GNPOld, LocalName, GovernmentForm, HeadOfState, Capital, Code2)
FROM world.country
union all 
select count(*) from 
(
SELECT Code, Name, Continent, Region, SurfaceArea, IndepYear, Population, LifeExpectancy, GNP, GNPOld, LocalName, GovernmentForm, HeadOfState, Capital, Code2
FROM world.country
group by Code, Name, Continent, Region, SurfaceArea, IndepYear, Population, LifeExpectancy, GNP, GNPOld, LocalName, GovernmentForm, HeadOfState, Capital, Code2
) a;

查询结果如下:

发现使用count(distinct xxx)后的结果居然和group by 去重的数据不一致;

不用怀疑,就是NULL引起的࿰

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值