2015-10-14 176 views
0

select語句返回位於獨特城市和州中的每個供應商的名稱,城市和州(即排除與另一個供應商具有相同城市和州的供應商)SQL Server - 相關子查詢/自加入

SELECT 
    VendorName, VendorCity, VendorState 
FROM 
    Vendors 
WHERE 
    VendorState + VendorCity NOT IN (SELECT VendorState + VendorCity 
            FROM Vendors 
            GROUP BY VendorState + VendorCity 
            HAVING COUNT(*) > 1) 
ORDER BY 
    VendorState, VendorCity; 

備選答案

SELECT 
    VendorName, VendorCity, VendorState 
FROM 
    Vendors AS Vendors_Main 
WHERE 
    VendorCity + VendorState NOT IN (SELECT VendorCity + VendorState 
            FROM Vendors AS Vendors_Sub 
            WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID) 
ORDER BY 
    VendorState, VendorCity; 

我明白了第一個答案,而不是替代查詢。混亂點:下面的行不會返回0行,因爲它們引用同一個表而沒有額外的where子句?

WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID) 

回答

0

WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID)不比較同一表的同一行。

相關子在邏輯上被執行一次用於在外部查詢的每一行,在你的情況下,它具有相同的VendorCity/VendorState組合檢查的行,但不同VendorIDs

其實我寧願直接翻譯成相關NOT EXISTS

SELECT VendorName, VendorCity, VendorState 
FROM Vendors AS Vendors_Main 
WHERE NOT EXISTS 
(
    SELECT * 
    FROM Vendors AS Vendors_Sub 
    WHERE Vendors_Sub.VendorCity = Vendors_Main.VendorCity -- same city 
    AND Vendors_Sub.VendorState = Vendors_Main.VendorState -- same state 
    AND Vendors_Sub.VendorID <> Vendors_Main.VendorID -- different vendor 
) 
ORDER BY VendorState, VendorCity; 

這可以防止誤報像'state' + 'acity''statea' + 'city'這兩個串聯爲「stateacity'並適用於任何類型的數據類型。

0
SELECT VendorName , 
     VendorCity , 
     VendorState 
FROM Vendors AS Vendors_Main 
WHERE VendorCity + VendorState NOT IN 
    (
     SELECT VendorCity + VendorState 
     FROM Vendors AS Vendors_Sub 
     WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID 
    ) 
ORDER BY VendorState ,VendorCity; 

子查詢

SELECT VendorCity + VendorState 
FROM Vendors AS Vendors_Sub 
WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID 

將不包括具有相同id主查詢返回的vendorCity + vendorState所有現有組合的每一行。將子查詢設想爲主查詢中每行的函數。

如果WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID不存在,則每個主要查詢行都將與子查詢中的自身相匹配,並且整個查詢將不返回任何行,因爲這些組合都不會是唯一的。