获取昨天从 PostgreSQL 开始到结束的记录

Jun*_*ooq 4 postgresql-9.3

目前我的应用程序正在运行超过 2 个 dbs,其中snapshotDB一个是evercamDB。我们snapshotDB正在保存记录,现在它想要检索它们,当前正在使用此查询

select camera_id,count(*) as snapshot_count 
from snapshots 
where snapshot_id in (select snapshot_id 
                      from snapshots 
                      where created_at = 'now'::date - 1) 
group by camera_id
Run Code Online (Sandbox Code Playgroud)

我想要的是获取snapshots今天正在考虑的记录2016-01-21,并且我想获取昨天的所有记录。'2016-01-20 00:00:00''2016-01-20 23:59:59''now'::date - 1我真的不知道如何以我所写的格式绑定时间。

我想输入这个日期和时间,(select snapshot_id from snapshots where created_at = 'now'::date - 1)以便我可以获得我想要的记录。

任何建议或帮助将不胜感激

小智 6

您需要将created_at其转换为date- 这将消除时间。

now()还包含一个时间,所以你需要使用current_date

最后,IN (..)不需要 your ,您可以直接在where子句中应用该条件:

select camera_id, count(*) as snapshot_count 
from snapshots 
where created_at::date = current_date - 1
group by camera_id;
Run Code Online (Sandbox Code Playgroud)

请注意,上面不会使用索引created_at。如果性能不可接受并且条件受益于使用索引,则可以使用如下内容:

select camera_id, count(*) as snapshot_count 
from snapshots 
where created_at >= date_trunc('day', current_timestamp) - interval '1' day
  and create_at < date_trunc('day', current_timestamp)
group by camera_id;
Run Code Online (Sandbox Code Playgroud)