如何使用更新的值每天运行PostgreSQL查询?

时间:2017-06-26 19:37:26

标签: sql postgresql scheduled-tasks

SQL新手,但是想为朋友学习/做一份工作。我有一个查询设置,返回当​​天的预订数量。示例摘录:

...
WHERE be.event IN ('instant_approve', 'approve') AND TO_CHAR(be.created_at, 'yyyy-mm-dd') BETWEEN '2017-06-26' AND '2017-06-26';

现在,此查询仅在今天设置。如何设置它以便明天查询执行'2017-06-27'等等?这可能吗?

2 个答案:

答案 0 :(得分:0)

内置函数now()为您提供事务开始的时间戳(CURRENT_TIMESTAMP伪常量是其“别名”,是SQL标准的一部分,但我更喜欢使用该函数)

另一个函数date_trunc()为您提供了“截断”时间戳,您可以选择如何截断它。例如,date_trunc('day', now())将为您提供当天开始的日期/时间。

此外,您可以轻松地添加或减去间隔,因此这里有一个示例,为您提供当前和下一天的开头:

select
  date_trunc('day', now()) cur_day_start,
  date_trunc('day', now() + interval '1 day') as next_day_start
;

此外,我不会在to_char()列的顶部使用created_at或其他任何内容 - 这将不允许Postgres规划者在此字段的顶部使用索引。如果您确实想使用to_char(),请考虑在to_char(created_at, 'yyyy-mm-dd')上添加功能索引。

以下是我将如何检索2017年7月26日生成的记录:

where
  created_at between '2017-06-26' and '2017-06-27'

(从文本到时间戳的隐式类型转换)

这相当于

where
  created_at >= '2017-06-26'
  and created_at <= '2017-06-27'

- 所以2017年7月26日生成的所有时间戳都将匹配。对于此类查询,Postgres将使用为created_at列创建的常规索引(如果有)。

“动态”版本:

where
  created_at between
    date_trunc('day', now())
    and date_trunc('day', now()) + interval '1 day'

答案 1 :(得分:0)

在条件之间使用current_date内置函数,它只适用于今天的预订。 ......... WHERE bevent IN('instant_approve','approve')AND TO_CHAR(be.created_at,'yyyy-mm-dd')= current_date;