2011-11-02 46 views
0

我正在開發一個集成項目,並創建了一個批處理日誌表,我已經存儲了哪些組合已經導出,然後根據該批處理日誌表檢查新數據。它工作得很好,只要我大多隻是存儲在batchlog表中的一個ID,假設客戶ID,然後選擇從客戶表中的新行是這樣的:如何在SQL中有一組組合作爲條件?

SELECT * 
FROM Customer 
WHERE CusId NOT IN (SELECT CusID FROM IntegrationBatchlog) 

不過,現在的解決方案是更爲複雜和同一行從Customer表導出幾次並結合其他數據,所以現在我有幾個單獨的存儲過程和IntegrationBatchlog表(CusID,OrdertypeID和PaymentMethod)中的更多列以及我的select中的join子句,所以現在更像。

SELECT * FROM Customer c 
JOIN.... 
JOIN... 
JOIN... 
WHERE there is not a row with that CusID AND OrderTypeID AND PaymentMethod in batchlog table yet. 

所以在這裏我應該檢查這是否精確組合已經出口,但是你怎麼做,當你有一個像在batchlog三表幾個ID列和要排除那些行,其中所有三個ID在batchlog表中已經存在於同一行中?

回答

0

一種方法是做一個LEFT JOIN到IntegrationBatchLog表,只能插入不存在的行。

select * 
from Customer c 
LEFT OUTER JOIN IntegrationBatchLog i 
    on c.CusId = i.CusId 
    and c.OrderTypeID = i.OrderTypeID 
    and c.PaymentMethod = i.PaymentMethod 
where 
    i.CusId is null 
0

使用EXISTS而不是IN。這允許多個列匹配

這是標準的SQL

SELECT * FROM Customer c 
JOIN.... 
JOIN... 
JOIN... 
WHERE NOT EXISTS (
     SELECT * FROM IntegrationBatchlog I 
       WHERE C.CusID = I.CusID 
          AND C.OrderTypeID = I.OrderTypeID 
          AND C.PaymentMethod = I.PaymentMethod) 
0
SELECT ... 
FROM Customer c JOIN ... 
WHERE NOT EXISTS (SELECT * 
        FROM IntegrationBatchLog I 
        WHERE I.CusID = c.CusId AND 
         I.OrderTypeId = c.OrderTypeID ...) 
0

也許NOT EXISTS就在這裏工作。下面是從MySQL文檔爲例(我不知道你的DB) - http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

第二個例子:

「什麼樣的商店出現在任何城市?」

SELECT DISTINCT store_type FROM stores 
    WHERE NOT EXISTS (SELECT * FROM cities_stores 
        WHERE cities_stores.store_type = stores.store_type); 

也許你可能是:

SELECT * FROM Customer c 
JOIN.... 
JOIN... 
JOIN... 
WHERE NOT EXISTS ( 
    SELECT * FROM batchlog WHERE 
     c.CusID = batchlog.CusID AND 
     c.OrderTypeID = batchlog.OrderTypeID AND 
     c.PaymentMethod = batchlog.PaymentMethod 
)