2010-08-19 51 views
1

我有一個相關的子查詢,它將返回一個數量列表,但我需要最高數量,並且只有最高數量。所以我試圖通過1的LIMIT來引入一個命令來實現這一點,但是MySQL會拋出一個錯誤,指出它還不支持子查詢中的限制。有關如何解決此問題的任何想法?在相關子查詢中的MySQL限制

SELECT Product.Name, ProductOption.Name, a.Qty, a.Price, SheetSize.UpgradeCost, 
     FinishType.Name, FinishOption.Name, FinishTierPrice.Qty, FinishTierPrice.Price 
FROM `Product` 
    JOIN `ProductOption` 
     ON Product.idProduct = ProductOption.Product_idProduct 
    JOIN `ProductOptionTier` AS a 
     ON a.ProductOption_idProductOption = ProductOption.idProductOption 
    JOIN `PaperSize` 
     ON PaperSize.idPaperSize = ProductOption.PaperSize_idPaperSize 
    JOIN `SheetSize` 
     ON SheetSize.PaperSize_idPaperSize = PaperSize.idPaperSize 
    JOIN `FinishOption` 
     ON FinishOption.Product_idProduct = Product.idProduct 
    JOIN `FinishType` 
     ON FinishType.idFinishType = FinishOption.Finishtype_idFinishType 
    JOIN `FinishTierPrice` 
     ON FinishTierPrice.FinishOption_idFinishOption = FinishOption.idFinishOption 
WHERE Product.idProduct = 1 
    AND FinishTierPrice.idFinishTierPrice IN (SELECT FinishTierPrice.idFinishTierPrice 
               FROM `FinishTierPrice` 
               WHERE FinishTierPrice.Qty <= a.Qty 
               ORDER BY a.Qty DESC 
               LIMIT 1) 

回答

3

這是經常出現的greatest-n-per-group問題的變體。

您需要單行表單FinishTierPrice(稱爲p1),匹配FinishOption和最大的數量,但仍小於或等於ProductOptionTier的數量。

一種方法是嘗試匹配FinishTierPrice中的第二行(p2),該行具有相同的FinishOption和更大的數量。如果不存在這樣的行(使用外連接並測試它爲NULL),則p1找到的行最大。

SELECT Product.Name, ProductOption.Name, a.Qty, a.Price, SheetSize.UpgradeCost, 
     FinishType.Name, FinishOption.Name, FinishTierPrice.Qty, FinishTierPrice.Price 
FROM `Product` 
    JOIN `ProductOption` 
     ON Product.idProduct = ProductOption.Product_idProduct 
    JOIN `ProductOptionTier` AS a 
     ON a.ProductOption_idProductOption = ProductOption.idProductOption 
    JOIN `PaperSize` 
     ON PaperSize.idPaperSize = ProductOption.PaperSize_idPaperSize 
    JOIN `SheetSize` 
     ON SheetSize.PaperSize_idPaperSize = PaperSize.idPaperSize 
    JOIN `FinishOption` 
     ON FinishOption.Product_idProduct = Product.idProduct 
    JOIN `FinishType` 
     ON FinishType.idFinishType = FinishOption.Finishtype_idFinishType 
    JOIN `FinishTierPrice` AS p1 
     ON p1.FinishOption_idFinishOption = FinishOption.idFinishOption 
     AND p1.Qty <= a.Qty 
    LEFT OUTER JOIN `FinishTierPrice` AS p2 
     ON p2.FinishOption_idFinishOption = FinishOption.idFinishOption 
     AND p2.Qty <= a.Qty AND (p2.Qty > p1.Qty OR p2.Qty = p1.Qty 
      AND p2.idFinishTierPrice > p1.idFinishTierPrice) 
WHERE Product.idProduct = 1 
    AND p2.idFinishTierPrice IS NULL