2013-05-11 77 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