2014-01-13 196 views
0

我可以知道爲什麼以下2個查詢返回不同的值。我想要第一個使用LEFT OUTER JOIN的確切結果。請幫忙。DB2:NOT EXISTS和LEFT OUTER JOIN

select count(a.ADDRESS_ID) from ADDRESS a where a.MEMBER_ID >= 50000000 and a.MEMBER_ID <= 999999999 and a.STATUS='T' and a.LASTCREATE < (current timestamp - 42 days) 
    and not exists (select 1 from ORDERS o where o.ADDRESS_ID = a.ADDRESS_ID) 
    and not exists (select 1 from ORDERITEMS oi where oi.ADDRESS_ID = a.ADDRESS_ID or oi.ALLOCADDRESS_ID = a.ADDRESS_ID) 
    and not exists (select 1 from HD_MEMBER_SUBSCR ms where ms.ADDRESS_ID = a.ADDRESS_ID) 
fetch first 800000 rows only for read only with ur; 


select count(ADDRESS_ID) FROM ADDRESS 
WHERE MEMBER_ID >= 50000000 
    AND MEMBER_ID < 999999999 
    AND STATUS = 'T' 
    AND LASTCREATE < (CURRENT_TIMESTAMP - 42 DAYS) 
    AND ADDRESS_ID IN (
    SELECT a.ADDRESS_ID 
    FROM ADDRESS a 
    LEFT OUTER JOIN ORDERS o 
     ON o.ADDRESS_ID = a.ADDRESS_ID AND o.ADDRESS_ID IS NULL 
    LEFT OUTER JOIN ORDERITEMS oi 
     ON oi.ADDRESS_ID = a.ADDRESS_ID AND oi.ADDRESS_ID IS NULL 
    LEFT OUTER JOIN ORDERITEMS oi2 
     ON oi2.ALLOCADDRESS_ID = a.ADDRESS_ID AND oi2.ALLOCADDRESS_ID IS NULL 
    LEFT OUTER JOIN HD_MEMBER_SUBSCR hms 
     ON hms.ADDRESS_ID = a.ADDRESS_ID AND hms.ADDRESS_ID IS NULL 
    FETCH FIRST 800000 ROWS ONLY 
); 

回答

0

這裏有兩方面的原因:

(1)您在獲取行的數量有限,沒有order by條款。行可以以任意順序返回,並且前兩個查詢的前800,000可能不相同。

(2)一個或多個連接有多個匹配。這會導致結果集中出現重複。

+0

我想要使用LEFT OUTER JOIN的第一個查詢的確切的同上。你能幫我嗎? – Samy

+0

@ user3175639。 。 。爲什麼?以這種方式構建一個相當複雜的查詢,並且您已經有了它。 –