語法是你的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')
嗯,我試過了,仍然沒有結果。我也試過使用間隔「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