2013-07-24 62 views
0

我有一個這樣的SQL:級聯SQL與不存在

SELECT distinct * 
FROM LETTRE_VOIT_TEMP where NOT EXISTS 
(
    SELECT * 
    FROM LETTRE_VOIT_FINAL lv 
    where lv.NOID  = LETTRE_VOIT_TEMP.NOID 
    AND lv.CODE_DEST = LETTRE_VOIT_TEMP.CODE_DEST 
    AND lv.CODE_CLIENT = LETTRE_VOIT_TEMP.CODE_CLIENT 
    AND (LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL IS NULL OR lv.NO_ORDRE_CUMMUL = LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTURE  IS NULL OR lv.DATE_CLOTURE  = LETTRE_VOIT_TEMP.DATE_CLOTURE) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL IS NULL OR lv.DATE_CLOTUR_REEL = LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL) 

) 

它工作得很好,但問題是當表LETTRE_VOIT_FINAL內容多的數據,那麼它會減緩請求。

,所以我改變這樣的:

SELECT distinct * 
FROM LETTRE_VOIT_TEMP where NOT EXISTS 
(
    SELECT * 
    FROM LETTRE_VOIT_FINAL lv 
    where lv.NOID  = LETTRE_VOIT_TEMP.NOID 
    AND lv.CODE_DEST = LETTRE_VOIT_TEMP.CODE_DEST 
    AND lv.CODE_CLIENT = LETTRE_VOIT_TEMP.CODE_CLIENT 
    AND (LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL IS NULL OR lv.NO_ORDRE_CUMMUL = LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTURE  IS NULL OR lv.DATE_CLOTURE  = LETTRE_VOIT_TEMP.DATE_CLOTURE) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL IS NULL OR lv.DATE_CLOTUR_REEL = LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL) 
    --AND lv.date_cloture between DATEADD(dd, -4, GETDATE()) and DATEADD(dd, +4, GETDATE()) 
    AND lv.DATE_CLOTUR_REEL = @DATE_CLOTUR_REEL 
) 

如我所料它不能正常工作。

我想先選擇所有LETTRE_VOIT_FINAL WHERE DATE_CLOTUR_REEL = @DATE_CLOTUR_REEL,然後與LETTRE_VOIT_TEMP比較。

我該怎麼做?

回答

0

把它放在子查詢中。子查詢將首先對其進行過濾,然後外部查詢將進行比較。

SELECT distinct * 
FROM LETTRE_VOIT_TEMP where NOT EXISTS 
(
    SELECT * 
    FROM (
     SELECT * 
     FROM LETTRE_VOIT_FINAL 
     WHERE lv.DATE_CLOTUR_REEL = @DATE_CLOTUR_REEL 
     ) lv  
    where lv.NOID  = LETTRE_VOIT_TEMP.NOID 
    AND lv.CODE_DEST = LETTRE_VOIT_TEMP.CODE_DEST 
    AND lv.CODE_CLIENT = LETTRE_VOIT_TEMP.CODE_CLIENT 
    AND (LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL IS NULL OR lv.NO_ORDRE_CUMMUL = LETTRE_VOIT_TEMP.NO_ORDRE_CUMMUL) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTURE  IS NULL OR lv.DATE_CLOTURE  = LETTRE_VOIT_TEMP.DATE_CLOTURE) 
    AND (LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL IS NULL OR lv.DATE_CLOTUR_REEL = LETTRE_VOIT_TEMP.DATE_CLOTUR_REEL) 
    --AND lv.date_cloture between DATEADD(dd, -4, GETDATE()) and DATEADD(dd, +4, GETDATE()) 
)