這兩種選擇,對我,提取似乎並不複雜
where 16 between extract(hour from start_ts) and extract(hour from end_ts)
where '16' between to_char(start_ts, 'hh24') and to_char(end_ts, 'hh24')
請注意,如果你把一個(start_ts,and_ts)上的普通索引,那麼這個查詢就不會使用它,而是會掃描整個表。你需要基於函數的索引來避免全表掃描http://www.dba-oracle.com/t_garmany_easysql_function_based_indexes_fbi.htm
還有第三個選項可以使用普通索引,但這不是你要求的,因爲在這裏你必須提供一天在這裏,不僅僅是小時
where to_timestamp('2011.12.06. 17', 'yyyy.mm.dd. hh24') between start_ts and end_ts
場的第四個選項將直接存儲開始和結束時間,而不是時間戳值。
繼承人的代碼我
select * from
(select
1 as id,
to_timestamp('2011.12.06. 16:10:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts,
to_timestamp('2011.12.06. 16:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts
from dual
union
select
2 as id,
to_timestamp('2011.12.06. 16:20:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts,
to_timestamp('2011.12.06. 17:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts
from dual
union
select
3 as id,
to_timestamp('2011.12.06. 17:30:32', 'yyyy.mm.dd. hh24:mi:ss') as start_ts,
to_timestamp('2011.12.06. 18:18:32', 'yyyy.mm.dd. hh24:mi:ss') as end_ts
from dual
)
where 16 between extract(hour from start_ts) and extract(hour from end_ts)
--where '16' between to_char(start_ts, 'hh24') and to_char(end_ts, 'hh24')
--where to_timestamp('2011.12.06. 17', 'yyyy.mm.dd. hh24') between start_ts and end_ts
;
十分感謝工程對它們進行測試。 – user1054247