SQL - 组合两个查询

时间:2012-11-26 00:23:45

标签: sql database ms-access subquery

我正在尝试合并这两个查询。

查询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;

我意识到确定哪些车辆是最昂贵的车辆,如果它们已经由客户拥有则无关紧要。由于第一个查询告诉我们哪些可用,我将如何将这两个结合起来?

1 个答案:

答案 0 :(得分: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为空的行。