请求postgresql查询协助
问题描述:
嘿大家。这是我的情况......我需要针对postgresql服务器制作一个sql查询语句,它将返回在过去5分钟内创建的所有记录,向下舍入到最低分钟。因此,如果cron在12:05:25.000处关闭查询,它需要查询自12:00:00.000以来创建的所有记录。所以我想我真的有两个问题。请求postgresql查询协助
下面是当前查询:
select * from callhistory where created>date_trunc('minute', timestamp (current_timestamp-interval '5' minute));
它不返回任何东西。另外,创建的字段格式为“2011-05-18 18:11:32.024”。
任何帮助,将不胜感激。
答
语法是你的date_trunc
是有点过:
select *
from callhistory
where created > date_trunc('minute', current_timestamp - interval '5' minute)
你也使用now()
in place of current_timestamp
:
select *
from callhistory
where created > date_trunc('minute', now() - interval '5' minute)
和示例:
=> create table stuff (created timestamp not null);
=> insert into stuff (created) values (current_timestamp);
-- Wait a could seconds...
=> insert into stuff (created) values (current_timestamp);
=> select * from stuff where created > date_trunc('minute', current_timestamp - interval '5' minute);
created
----------------------------
2011-06-01 11:32:55.672027
2011-06-01 11:33:00.182953
=> select * from stuff where created > date_trunc('minute', current_timestamp - interval '7' day);
created
----------------------------
2011-06-01 11:32:55.672027
2011-06-01 11:33:00.182953
UPDATE:外表像PostgreSQL版本8对于interval
的格式稍微严格一点,fine manual表示您应该使用interval '$n $unit'
,其中$n
是事物的数量,而$unit
是时间单位。版本9允许您在没有投诉的情况下说interval '$n' $unit
,但如果您不使用记录的格式,版本8会将您的时间间隔转换为0。所以,你应该将它用于版本8和版本9:
select *
from callhistory
where created > date_trunc('minute', current_timestamp - interval '5 minute')
答
这是我针对PostgreSQL 8.3服务器进行的一个示例测试。你没有提到你正在运行的版本。
select current_timestamp, to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp;
间隔减去5分钟,to_char()方法向下舍入到最接近的分钟。如果这是你正在寻找,那么查询应该看起来如下:
select * from callhistory where created > to_char((current_timestamp - '5 minutes'::interval), 'yyyy-mm-dd HH:mi:00')::timestamp
嗯,我试过了,仍然没有结果。我也试过使用间隔“7”日和间隔“1”月,但没有运气。最新的记录是在27日创建的,所以他们中的一个应该返回一些东西。它可能与包括时区在内的时间戳格式有关吗? – Matthew 2011-06-01 17:15:24
'CURRENT_TIMESTAMP'很好 - 'now()'虽然完全等价,但是不标准。 – 2011-06-01 17:23:06
@Milen:这就是为什么我在原始答案中更正了关于'current_timestamp'的评论。 – 2011-06-01 17:27:22