0

我有这两个我正在尝试组合的查询。

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

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

4

1 回答 1

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 为空的行。

于 2012-11-26T23:21:16.303 回答