You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LEFT JOIN后无法统计不匹配NULL行的问题解决咨询

解决Left Join后统计不匹配行的问题

我来帮你分析下问题出在哪,以及怎么修正:

问题原因

你的Left Join结果确实有一行不匹配的记录(A | NULL),但你用了count(tb2.col2)来统计——而count(列名)的特性是自动忽略NULL值,所以这行的tb2.col2是NULL,不会被计入统计,最终返回0,这和你预期的结果不符。

解决方案

你可以通过以下几种方式正确统计不匹配的行:

方法1:使用count(*)统计所有行

count(*)会统计Left Join后的所有行,包括tb2.col2为NULL的记录:

select count(*) 
from (select unnest(array['A','B']) col1) tb1 
left join (select unnest(array['B','C']) col2) tb2 on tb1.col1=tb2.col2 
where tb2.col2 IS NULL;

方法2:统计左表的非NULL列

因为Left Join后左表tb1的行都会保留,且你的tb1.col1没有NULL值,所以统计tb1.col1也能得到正确结果:

select count(tb1.col1) 
from (select unnest(array['A','B']) col1) tb1 
left join (select unnest(array['B','C']) col2) tb2 on tb1.col1=tb2.col2 
where tb2.col2 IS NULL;

方法3:用Case语句手动统计

如果想更清晰地表达统计逻辑,可以用sum结合case来计数:

select sum(case when tb2.col2 is null then 1 else 0 end) as unmatched_count
from (select unnest(array['A','B']) col1) tb1 
left join (select unnest(array['B','C']) col2) tb2 on tb1.col1=tb2.col2;

以上三种方法都会返回你预期的1,完美解决统计不匹配行的问题。

内容的提问来源于stack exchange,提问作者HP.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:34:59