1

我有三张桌子:

  • order
  • orderline(有orderID
  • orderactions(有orderID

然后我需要SUM(of orderline.price)SUM(of orderactions.price)per orderID

当我使用:

    SELECT order.ID, SUM(orderlines.price), SUM(orderactions.price) 
    FROM order 
    LEFT JOIN orderlines ON orderlines.orderID=order.ID
    LEFT JOIN orderactions ON orderactions.orderID=order.ID
    WHERE order.ID=@orderID
    GROUP BY order.ID

我得到了一个结果,orderactions这个结果相当于SUM(orderactions.price)*quantity这个 order.ID 的 orderlines

我找到的唯一解决方案,它给了我一个正确的结果,是每个“SUM”表的子查询:

SELECT order.ID
, (SELECT SUM(orderlines.price) FROM orderlines WHERE orderlines.orderId=order.ID)
, (SELECT SUM(orderactions.price) FROM orderactions WHERE orderactions.orderId=order.ID)
FROM order
WHERE order.ID=@orderID

问题:是否有其他(更快)解决方案,因为子查询很慢,我们尽量不使用它们?

4

2 回答 2

1

Since your select only runs the two very simple subqueries once each, I'd say you're pretty close to optimal for your query. There is no need to add a JOIN unless the queries are correlated in some way.

The slow part about subqueries is usually that the database may (if you're not careful how you write your query) non obviously execute them more than once. This normally happens if they depend on external values that may change per row, ie when you JOIN them in some way.

Your subqueries are straight forward enough and not using any external values other than your constant, so in your case, they only execute once each, and there is nothing in them that is simplified by adding a JOIN.

于 2012-10-08T18:00:57.647 回答
1

取决于您的数据,这种方式可以成为解决方案:

    SELECT order.ID, 
    SUM(CASE WHEN orderlines.orderID IS NOT NULL THEN orderlines.price ELSE 0 END), 
    SUM(CASE WHEN orderactions.orderID IS NOT NULL THEN orderactions.price ELSE 0 END) 
FROM order 
LEFT JOIN orderlines ON orderlines.orderID=order.ID
LEFT JOIN orderactions ON orderactions.orderID=order.ID
WHERE order.ID=@orderID
GROUP BY order.ID
于 2012-10-08T18:23:04.737 回答