为何WHERE子句下SQL查询计数总和不符?异常原因排查
第二个SQL查询计数低于预期的原因分析
你的address_data表里存在city或street字段为NULL的记录,这就是问题所在。
核心逻辑解释
- 第一个查询
select count(*) from address_data where city = 'New York' and street = 'Mainstreet'只会统计同时满足两个条件的非NULL记录,所以返回100条是正常的。 - 第二个查询的
where not (city = 'New York' and street = 'Mainstreet'),当city或street为NULL时,city = 'New York'或street = 'Mainstreet'的运算结果是UNKNOWN,整个括号内的表达式结果也是UNKNOWN,而NOT UNKNOWN依然是UNKNOWN。SQL的WHERE子句只会保留运算结果为TRUE的记录,这些结果为UNKNOWN的行就被过滤掉了,不会被计入总数。
修正后的查询
如果要统计所有不满足city = 'New York'且street = 'Mainstreet'的记录(包括含NULL的行),可以修改查询为:
select count(*) from address_data where not (city = 'New York' and street = 'Mainstreet') or city is null or street is null;
或者更直接的方式,用总记录数减去第一个查询的结果:
select (select count(*) from address_data) - ( select count(*) from address_data where city = 'New York' and street = 'Mainstreet' ) as non_target_count;
内容的提问来源于stack exchange,提问作者jonas
相关产品推荐
相关产品推荐

