简体   繁体   English

为什么此查询不起作用

[英]Why doesn't this query work

There are two tables, both have only one column. 有两个表,都只有一列。 delete_DimCSI has 196194 rows and delete_FRO has 195740 rows. delete_DimCSI具有196194行,而delete_FRO具有195740行。 I am looking for rows that exist in delete_DimCSI table but not existing in delete_FRO table. 我正在寻找存在于delete_DimCSI表中但不存在于delete_FRO表中的行。

This is the query I usually use and it worked so far: 这是我通常使用的查询,到目前为止它仍然有效:

select PK_CSI from delete_DimCSI
where PK_CSI not in (select FK_CSI from delete_FRO)

It returns 0 rows. 它返回0行。

Then I created this one: 然后我创建了这个:

select PK_CSI, FK_CSI from delete_DimCSI
LEFT OUTER JOIN delete_FRO FRO on FK_CSI = PK_CSI
where FK_CSI is null

It returns 455 rows. 它返回455行。

Any idea why the first query doesn't return any row? 知道为什么第一个查询不返回任何行吗?

You probably have NULL s in FK_csi 您可能在FK_csiNULL

select PK_CSI from delete_DimCSI
where PK_CSI not in (select FK_CSI from delete_FRO WHERE FK_CSI IS NOT NULL)

Look here for an explanation. 在这里查看说明。

NOT IN behaves strangely when the subquery has NULL values. 当子查询具有NULL值时, NOT IN行为会很奇怪。 In that case, it returns either NULL or false -- neither of which is treated as true. 在这种情况下,它返回NULL或false -都不将其视为true。

For this reason, I recommend using NOT EXISTS rather than NOT IN . 因此,我建议使用NOT EXISTS而不是NOT IN The semantics are more what you expect: 语义更符合您的期望:

select PK_CSI
from delete_DimCSI d
where not exists (select 1 from delete_FRO f where f.FK_CSI = d.PK_CSI);

Of course, you can also add an explicit where f.FK_CSI = NULL` as Mihai suggests. 当然,您也可以按照Mihai的建议where f.FK_CSI = NULL`处添加一个明确的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM