Oracle 中的DATE 不仅有日期部分,还有时间部分。在查询数据时,这可能会导致令人惊讶的结果,例如查询
with v_data(pk, dt) as (
select 1, to_date('2014-06-25 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual union all
select 2, to_date('2014-06-26 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual union all
select 3, to_date('2014-06-27 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual)
select * from v_data where dt = date '2014-06-25'
将不返回任何行,因为您在午夜与 2014-06-25 进行比较。
通常的解决方法是使用TRUNC() 去掉时间部分:
with v_data(pk, dt) as (
select 1, to_date('2014-06-25 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual union all
select 2, to_date('2014-06-26 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual union all
select 3, to_date('2014-06-27 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual)
select * from v_data where trunc(dt) = date '2014-06-25'
解决此问题的其他不太常用的方法包括:
- 用
to_char('YYYY-MM-DD') 转换两个日期并检查是否相等
- 使用 between 子句:
WHERE dt between date '2014-06-25' and date '2014-06-26'