数据库
首页 > 数据库> > 相关子查询中的MySQL LIMIT

相关子查询中的MySQL LIMIT

作者:互联网

我有一个相关的子查询,该子查询将返回数量列表,但我需要的数量最高,也只有最高的数量.因此,我试图引入一个以LIMIT为1的顺序来实现此目的,但是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)

解决方法:

这是经常出现的每组最多n个问题的变体.

您需要单行形式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

标签:correlated-subquery,mysql,greatest-n-per-group
来源: https://codeday.me/bug/20191012/1903227.html