2012-11-26 233 views
0

我想要結合這兩個查詢。SQL - 結合兩個查詢

查詢1 - 這告訴我我的清單中有所有車輛。含義不在所有權表中:

SELECT VEHICLE.* 
FROM VEHICLE 
WHERE NOT EXISTS 
(SELECT NULL FROM OWNERSHIP WHERE VEHICLE.VEH_ID= OWNERSHIP.VEH_ID); 

查詢2 - 這個告訴我哪個車是每個品牌的最高價格。

SELECT B.BRAND_ID, B.BRAND_NAME, M.MODEL_NAME, C.CLASS_NAME, V.VEH_ID, V.VEH_YEAR, V.VEH_PRICE 

FROM (((VEHICLE AS V INNER JOIN CLASS AS C ON V.CLASS_ID = C.CLASS_ID) 
INNER JOIN MODEL AS M ON M.MODEL_ID = V.MODEL_ID) 
INNER JOIN BRAND AS B ON B.BRAND_ID = M.BRAND_ID) 
INNER JOIN (SELECT M.BRAND_ID, MAX(V.VEH_PRICE) AS VEH_PRICE FROM VEHICLE AS V 
INNER JOIN MODEL AS M ON M.MODEL_ID = V.MODEL_ID GROUP BY M.BRAND_ID) 

AS derived ON (v.VEH_PRICE = derived.VEH_PRICE) AND (b.BRAND_ID = derived.BRAND_ID) 
ORDER BY 7 DESC; 

我意識到,確定哪些車輛是最昂貴的車輛是無關緊要的,如果他們已經被客戶所有。由於第一個查詢告訴我們哪些是可用的,我將如何結合這兩個?

回答

2

我無法測試您的查詢,但認爲這是你在找什麼:

SELECT 
    B.BRAND_ID, 
    B.BRAND_NAME, 
    M.MODEL_NAME, 
    C.CLASS_NAME, 
    V.VEH_ID, 
    V.VEH_YEAR, 
    V.VEH_PRICE 
FROM 
    (((VEHICLE AS V INNER JOIN CLASS AS C ON V.CLASS_ID = C.CLASS_ID) 
    INNER JOIN MODEL AS M ON M.MODEL_ID = V.MODEL_ID) 
    INNER JOIN BRAND AS B ON B.BRAND_ID = M.BRAND_ID) 
    INNER JOIN (SELECT M.BRAND_ID, MAX(V.VEH_PRICE) AS VEH_PRICE 
       FROM VEHICLE AS V 
        INNER JOIN MODEL AS M 
        ON M.MODEL_ID = V.MODEL_ID 
       WHERE 
       NOT EXISTS 
        (SELECT NULL FROM OWNERSHIP 
        WHERE V.VEH_ID=OWNERSHIP.VEH_ID) 
       GROUP BY M.BRAND_ID) AS derived 
    ON (v.VEH_PRICE = derived.VEH_PRICE) 
    AND (b.BRAND_ID = derived.BRAND_ID) 
WHERE 
    NOT EXISTS 
    (SELECT NULL FROM OWNERSHIP 
    WHERE V.VEH_ID=OWNERSHIP.VEH_ID) 
ORDER BY 7 DESC; 

你必須排除在你計算的最高價格爲每一個品牌的子查詢已經擁有汽車,但同樣在外部查詢中,排除與沒有擁有者的車輛的最大價格相同的所有車輛。

除了使用NOT EXISTS子句,我還建議在子查詢和外部查詢中再添加一個帶有OWNERSHIP的LEFT JOIN,並且只取OWNERSHIP.VEH_ID爲空的行。

+0

還有另外一個'Vehicle AS V'條款,你沒有'修復',但我認爲這不會對結果產生影響。 –