小编jdi*_*n04的帖子

postgres 查询性能:视图与函数

我有一个场景,我需要运行工资报告。该报告计算特定日期范围内按员工分组的工资金额。

例如,当运行 2016-11-01 到 2016-11-30 的报告时,我会看到以下结果:

Staff Id    Total
------------------
1           123.00
2           439.22
Run Code Online (Sandbox Code Playgroud)

我对上述报告使用以下查询:

select 
    user_id as staff_id,
    sum(amount) as total
from transaction
where
    business_id = <business_id> and
    type = 'staff' and
    kind = 'commission' and
    created_at between <start_date> and <end_date>
group by
    user_id;
Run Code Online (Sandbox Code Playgroud)

我正在尝试根据以下要求确定优化此查询性能的最佳方法:

  • 结果将根据business_idstart_dateend_date
  • 数据应该始终是新鲜的

看来视图和函数都可以完成这项工作,但我并不能 100% 确定哪种方法是考虑到需求的最佳方法。

旁注:如果能够根据上面提到的参数来缓存数据就太好了,但是数据库方面似乎没有很好的解决方案。如我错了请纠正我!

附加信息:

  • 我正在运行 Postgres 9.6
  • 我在表中的business_idtypekind和列上有索引。这些都是单列、btree 索引。user_idcreated_attransaction

postgresql performance postgresql-performance

7
推荐指数
1
解决办法
9946
查看次数