Bar*_*chs 8 postgresql best-practices aggregate alias
我知道我必须写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)
总和仅计算一次。
我使用以下方法验证了这一点
create table mytable (id int, hours int);
insert into mytable values (1, 60);
select sum(hours) from mytable group by id having sum(hours) > 50;
Run Code Online (Sandbox Code Playgroud)
然后使用调试器检查调用了多少次int4_sum(聚合背后的转换函数sum):一次。