小编Dav*_*dge的帖子

使用 SUM() 两次是否次优?

我知道我必须写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)

postgresql best-practices aggregate alias

8
推荐指数
1
解决办法
1542
查看次数

标签 统计

aggregate ×1

alias ×1

best-practices ×1

postgresql ×1