Sql 不在操作员问题中

Sql 不在操作员问题中,sql,oracle,plsql,Sql,Oracle,Plsql,我的问题是: Select a.* from Table1 a, Table2 b Where a.tid=b.tid and b.createddate=(Select max(createddate) from Table2) and a.tid not in (Select distinct tid from Table3); 问题是我知道这应该返回一些有效的输出,但它没有。向我们发送a.tid中的最后一行,而不是从表3中选择不同的tid;如果我用硬编码的值(如'T001'、'T00

我的问题是:

Select a.* from Table1 a, Table2 b
Where 
a.tid=b.tid and 
b.createddate=(Select max(createddate) from Table2) and
a.tid not in (Select distinct tid from Table3);
问题是我知道这应该返回一些有效的输出,但它没有。向我们发送a.tid中的最后一行,而不是从表3中选择不同的tid;如果我用硬编码的值(如'T001'、'T002'、'T003'、'T004'替换表3中的Select distinct tid),则它工作正常并返回数据


怎么了?我错过什么了吗?请提供帮助。

您的查询,稍微重写:

Select a.*
from Table1 a join
     Table2 b 
     on a.tid=b.tid 
where b.createddate=(Select max(createddate) from Table2) and
      a.tid not in (Select distinct tid from Table3)
这告诉我的是,表2中具有最大创建日期的tid位于表3中

要测试这一点,请从表2中获取最大创建日期。然后获取表1中与此最大值对应的所有记录。您将发现这些记录也在表3中

如果我不得不推测,您可能需要表2中每个表的最大创建日期,而不是总的最大创建日期

顺便说一下,在Oracle和大多数其他数据库中,最后一个子查询中的distinct是冗余的。在这种情况下,数据库应该足够智能,可以删除重复项。

尝试以下操作:

Select a.* from Table1 a, Table2 b
Where 
a.tid=b.tid and 
b.createddate=(Select max(createddate) from Table2) and
a.tid not in (Select tid from Table3 where tid is not null);
正如评论中提到的所有人一样,如果表3中至少有一行的tid值为空,则不会返回任何行。这是因为对Oracle null来说就像是说我不知道这个值是什么。Oracle不能肯定地说您搜索的值肯定不在您的子选择中,因为它不知道这个未知值实际上是什么。此外,文件中说它是这样工作的:

另一个选项是将查询编写为:

Select a.* from Table1 a, Table2 b
Where 
a.tid=b.tid and 
b.createddate=(Select max(createddate) from Table2) and
not exists (Select null from Table3 t3 where t3.tid = a.tid);

null的处理是not exists和not in之间的主要区别之一。

:手动运行查询从表3中选择distinct tid,如果此查询将任何记录返回为null,则not in将不会返回任何结果。因此,删除distinct,这对性能没有帮助。Gaurav该查询返回数据。RedFilter-谢谢,我已删除了distinct。@Ram:如果tid不是主键,只是为了确认旧版本,但goodie:Gordon否,则表3中具有最大创建日期的tid不在表2中,您是否可以将NOT IN查询重新写入为NOT IN Select tid,其中tid不为null。这是令人费解的:我假设了同样的事情,并要求他在评论中也这样做以确认,但正如他所说,tid返回数据:Craig,Gaurav是的,就是这样。一旦我在子查询中添加了tid,它就工作了。克雷格:非常感谢你的解释。@GauravSoni-这个问题是关于如何不在工作中的微妙之处。如果表3中有任何行的tid为空,那么无论其他数据是什么,他的原始查询都不会返回任何行。@Craig:我正试图用Ram找出相同的结果,否则你的解释会告诉一切:+1