date_part()
作品等extract()
,即它們將extract a subfield從源:
-- they will both yield 9 as result
select date_part('day', date '2015-01-09') "day part of 2015-01-09",
date_part('day', date '2015-02-09') "day part of 2015-02-09";
提取day(s)
因此不適合於選擇在過去24小時。類似地,提取hour(s)
將(幾乎)總是產生小於或等於24
。
提取day(s)
從interval
(這是減去2 timestamp
s的結果)有點不同。其結果可能取決於,區間是否合理,或不:
-- they will both yield 1 as result
select date_part('day', interval '1 day') "day part of 1 day",
date_part('day', interval '1 month 1 day') "day part of 1 month 1 day";
-- they will yield 1, 32 and 397 respectively
select date_part('day', timestamp '2015-02-09' - timestamp '2015-02-08') "interval 1",
date_part('day', timestamp '2015-02-09' - timestamp '2015-01-08') "interval 2",
date_part('day', timestamp '2015-02-09' - timestamp '2014-01-08') "interval 3";
根據事實,時間戳減法沒有給合理的時間間隔是不是最好的選擇,我想。你可以使用簡單的條件,以實現自己的目標:
-- if startdate is a timestamp:
where current_timestamp - interval '1 day' <= startdate
-- if startdate is a date:
where current_date - 1 <= startdate
如果要禁止將來的日期太(你的問題的標題所暗示的),你可以使用一個單一的between
條件:
-- if startdate is a timestamp:
where startdate between current_timestamp - interval '1 day' and current_timestamp
-- if startdate is a date:
where startdate between current_date - 1 and current_date
當心,一天不一樣24小時。 [有些日子有25或23](https://en.wikipedia.org/wiki/Daylight_saving_time#Procedure)。 – Schwern 2015-02-09 08:58:09
謝謝@Schwern它不適用於夏令時的國家。 – Pirinthan 2015-02-09 09:04:55
@Pirinthan現在也許不會,但事情會改變。斯里蘭卡?在過去的20年中,您的時區已更改三次,其中每個轉換可能會破壞此代碼。 – Schwern 2015-02-09 09:20:59