我知道我必须写SUM
两次,如果我想在HAVING
子句中使用它(否则使用派生表):
SELECT id,
sum(hours) AS totalhours
FROM mytable
GROUP BY id
HAVING sum(hours) > 50;
Run Code Online (Sandbox Code Playgroud)
我现在的问题是,这是否是次优的。作为程序员,这个查询看起来 DB 会计算两次总和。是这样,还是我应该依赖数据库引擎将为我做的优化?
更新:可比查询的解释:
postgres=> explain select sum(counttodo) from orderline group by orderlineid having sum(counttodo) > 100;
QUERY PLAN
--------------------------------------------------------------------
HashAggregate (cost=1.31..1.54 rows=18 width=8)
Filter: (sum(counttodo) > 100)
-> Seq Scan on orderline (cost=0.00..1.18 rows=18 width=8)
(3 rows)
Run Code Online (Sandbox Code Playgroud)