2013-05-11 79 views
1

我们有一个主表,10000个记录,其中5000条记录为status=completed,另有5000条记录status=incompleted使用NOT IN进行查询优化

应用程序维护的人有不同的种类...说users,visitors,admin ..

游客非常少(比如200个记录)......,当他们购买的东西在应用中appid获取与更新的状态完成= 。

我们需要谁拥有status!=completed

我知道,直接的方法是不错的表现了游客的appid ..(下一个)

select appid 
from application 
where status != completed and appid in (select appid from visitors) 

appid也包含在游客和以及在应用..作为应用程序包含5000完成和5000未完成

NOT IN (select appid from application where status=completed)也与IN (select appid from application where status=incompleted)

select v.appid 
from visitors v 
where v.appid not in (select appid from application where status = completed) 

是我第二次查询给出了1倍的查询性能相同..

如果NOT IN执行就像this..then是..

我下面写的语句。

for each v.appid in visitors{ 
    do not select the v.appid if v.appid is in by firing the query as below. 

    select appid 
    from application 
    where appid = v.appid and status = completed 
} 

将第二个查询大火,我上面所说的过程...

,以提供更好的性能相同,与1日查询可以我下面写一个..

select v.appid 
from visitors v 
where v.appid not in (select appid 
         from application 
         where status = completed and appid = v.appid) 

我如何编写第二个查询以便它与第一个查询执行相同的级别?

+1

有什么理由不使用连接 – Sunny 2013-05-11 05:52:47

+1

哪个RDBMS是这个吗? – 2013-05-11 07:47:09

+0

@DavidAldridge oracle dbms – 2013-05-11 08:59:17

回答

3

尝试使用NOT EXISTS条件:

select v.appid 
from visitors v 
where not exists 
(select 1 
from application a 
where a.status = 'completed' and a.appid = v.appid) 
+0

感谢您的信息... – 2013-05-11 09:02:36

+0

@pratapm:不客气。 – 2013-05-11 09:08:51

0

使用连接,而不是使查询更具可读性和效率。首先查询将转换为:

select 
     a.appid 
from 
     application a INNER JOIN 
     visitors v ON a.appid = v.appid 
where 
     a.status!='completed' 

利用当前的数据库服务器,interms的性能,它并没有多大意义,除非您有很多表大量的行。

+2

这会给出一个错误,因为'appid'不明确。它也可能给'status'一个错误。从多个表中进行选择时,我不会指定没有表别名的列,无论它是否含糊不清。 – hvd 2013-05-11 07:24:53

+1

这可能不会产生与IN子查询 – Magnus 2013-05-11 08:47:35

+0

@Magnus完全相同的结果,它如何不会产生与IN子查询相同的结果。 INNER JOIN将根据状态仅获取访问者和WHERE条件。 – Sunny 2013-05-13 18:03:56