与单独查询相比,联合查询产生更多结果

Joined query producing more results compared to solo query

我正在执行以下查询,该查询具有针对另一个 table 的内部联接。

select count(myTable.name) 
from sch2.sample_detail as myTable 
inner join sch1.otherTable as otherTable on myTable.name = otherTable.name 
where otherTable.is_valid = 1 
  and myTable.name IS NOT NULL;

这产生了 4912304 的计数。

以下是对单个 table(我的 table)的查询。

SELECT COUNT(myTable.name) 
from sch2.sample_detail as myTable 
where myTable.name IS NOT NULL;

这产生了 2864654 的计数。

但这怎么可能呢?两个查询都有子句 where myTable.name IS NOT NULL.

第二个查询不应该产生相同的结果,或者如果不是更多,因为第二个查询没有 otherTable.is_valid = 1 子句? 为什么内部联接会产生更多的结果?

第一次查询有什么需要修改的请指教,谢谢

内联、左联或交叉联可以复制行。 sch1.otherTable.name 不是唯一的,这会导致行重复,因为对于左侧 table 中的每一行,来自右侧 table 的所有对应行都被 selected,这是正常的连接行为。

要获取重复名称列表,请使用此查询并决定如何删除重复的行:过滤或不同或按 row_number 等过滤

select count(*) cnt,
       name
  from sch1.otherTable
having count(*)>1
order by cnt desc;

如果您需要 EXISTS(并且不需要来自其他表的 select 列),请使用 left semi join。 具有不同的子查询也可用于在连接和过滤之前预先聚合名称:

select count(myTable.name) 
from sch2.sample_detail as myTable 
LEFT SEMI JOIN (select distinct name from sch1.otherTable otherTable where otherTable.is_valid = 1 ) as otherTable on myTable.name = otherTable.name 
where myTable.name IS NOT NULL;