2011-06-01 83 views
0

嘿大家。這是我的情況......我需要針對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」。

任何幫助,將不勝感激。

回答

2

語法是你的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') 
+0

嗯,我試過了,仍然沒有結果。我也試過使用間隔「7」日和間隔「1」月,但沒有運氣。最新的記錄是在27日創建的,所以他們中的一個應該返回一些東西。它可能與包括時區在內的時間戳格式有關嗎? – Matthew 2011-06-01 17:15:24

+1

'CURRENT_TIMESTAMP'很好 - 'now()'雖然完全等價,但是不標準。 – 2011-06-01 17:23:06

+0

@Milen:這就是爲什麼我在原始答案中更正了關於'current_timestamp'的評論。 – 2011-06-01 17:27:22

0

這是我針對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