在查询中重用计算

时间:2012-06-01 19:47:16

标签: mysql sql

我想在我的数据库中创建一个包含少量逻辑的视图。这是检查产品的可用性。我已经创建了一个简化的架构a SQL Fiddle

但是,我需要在多列中重用一个值。这就是我想做的事情:

SELECT
    product.id AS id,
    SUM(IFNULL(purchase_product.amount,0)) AS amountSold,
    IFNULL(product.amountAvailable-amountSold,~0) AS amountAvailable,
    amountAvailable>0 AS isAvailable,
FROM product
    LEFT JOIN purchase_product ON purchase_product.product_id = product.id
    LEFT JOIN purchase ON purchase.id = purchase_product.purchase_id AND purchase.completed = TRUE
GROUP BY product.id

但这失败是因为我无法重复使用“amountSold”和“amountAvailable”。这让我选择重复计算或使用子查询(/使用SELECT连接/使用更多视图)。

这是我在小提琴中能够提出的最合理的妥协。 有更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:2)

我非常喜欢您当前的解决方案,我认为没有真正的问题,但我认为这可能会稍微简单一些:

SELECT  Product.ID, 
        COALESCE(AmountSold, 0) AS AmountSold,
        GREATEST(COALESCE(AmountAvailable, ~0) - COALESCE(AmountSold, 0), 0) AS AmountAvailable,
        COALESCE(AmountAvailable, ~0) - COALESCE(AmountSold, 0) > 0 AS IsAvailable
FROM    Product
        LEFT JOIN 
        (   SELECT  Product_ID, SUM(Amount) AS AmountSold
            FROM    Purchase_Product
                    INNER JOIN Purchase
                        ON Purchase.ID = Purchase_ID
            WHERE   Completed = 1
            GROUP BY Product_ID
        ) sold
            ON Sold.Product_ID = Product.ID;

唯一真正的变化是我在子查询中删除了对产品的引用,以减少表扫描的数量,并且还略微改变了计算的逻辑。

最后我在其中添加了GREATEST,只是为了解释可能存在的任何数据完整性问题,以便您永远不会有负面产品。

你可以做更多的子查询来增加查询的可读性,但几乎肯定不会提高性能。

SQL Fiddle显示了稍微改进的执行计划。

答案 1 :(得分:1)

您可以在带有连接的子查询中执行此操作:

select product.id, s.amountsold,
       IFNULL(product.amountAvailable-s.amountSold,~0) AS amountAvailable, 
       product.amountAvailable>0 AS isAvailable
       -- although you probably mean
       -- IFNULL(product.amountAvailable-s.amountSold,~0) > 0 as isAvailable
from product join
     (SELECT product.id AS id, 
             SUM(IFNULL(purchase_product.amount,0)) AS amountSold,
             IFNULL(product.amountAvailable-amountSold,~0) AS amountAvailable, 
             amountAvailable>0 AS isAvailable
      FROM product LEFT JOIN
            purchase_product
            ON purchase_product.product_id = product.id LEFT JOIN
            purchase
            ON purchase.id = purchase_product.purchase_id AND
               purchase.completed = TRUE
      GROUP BY product.id
    ) t
    on product.id = t.id

在其他数据库中,您可以使用Windows函数执行类似操作。但是,mysql不支持它们。

另外,我认为你希望isAvailable在你减去售出之后,所以我把它作为一个建议加入。