Select 不在另一个 ID 中的 ID table 不起作用?

Select IDs where ID not in another table not working?

我正在使用 Vertica SQL

两个表:

Table1
ID,Sales
1,50 
2,0
3,60
..

Table2
ID,sales
3,50
4,55
5,60
...

select count(distinct id) from table1 where sales >0; 
--returns about 50
select count(distinct id) from table2 where sales >0; 
--returns about 20

select count(distinct t1.id) from table1 t1 where t1.sales >0 and t1.id not in (select distinct(t2.id) from table2 t2 where t2.sales >0);
--returns 0

如果在给定条件下 table1 的记录多于 table2,这怎么可能?

ID 是 varchar,sales 是数字

提前致谢!

这是您的查询:

select count(distinct t1.id)
from table1 t1
where t1.sales > 0 and
      t1.id not in (select distinct t2.id from table2 t2 where t2.sales > 0);

not in 是一个危险的结构。如果子查询中的 any 行具有 idNULL 值,则 no 行根本不会返回外部查询。出于这个原因,我强烈建议对这样的逻辑使用 not exists

select count(distinct t1.id)
from table1 t1
where t1.sales > 0 and
      not exists (select 1from table2 t2 where t2.id = t1.id and t2.sales > 0);

您也可以通过连接来做到这一点:

SELECT COUNT(DISTINCT t1.id) as id_count
FROM table1 t1
LEFT JOIN
(SELECT DISTINCT id
 FROM table2
 WHERE sales > 0) sub
ON t1.id = sub.id
WHERE sub.id IS NULL
AND t1.sales > 0

它看起来不太漂亮,但可能有性能优势。