2016-02-24 90 views
1

我在做oracle中的日期比较。 当我执行下面与Oracle中的日期比较问题

select tr.x, tbi.y, to_char(tr.UPDATED_AT,'dd-mon-yyyy') 
from tbi, tb, tr 
where 
tbi.id=tb.id and 
tb.id=tr.id and 
tr.updated_at = to_date('23/02/2016', 'dd/MM/yyyy') 

代码没有行选择

但是,当我执行以下查询

select tr.x, tbi.y, to_char(tr.UPDATED_AT,'dd-mon-yyyy') 
from tbi, tb, tr 
where 
tbi.id=tb.id and 
tb.id=tr.id 
and 
tr.updated_at > to_date('23/02/2016', 'dd/MM/yyyy') 

我得到这样的结果

trx.x tbi.y TO_CHAR(TR.UPDATED_AT,'DD-MM-YYYY') 
123456 0 23-02-2016 
12345 0 23-02-2016 
123  0 23-02-2016 
123123 0 23-02-2016 

为什么>运营商显示日期相等,并且=没有显示相同的日期?

回答

1

您应该使用TRUNC()

select tr.x, tbi.y, to_char(tr.UPDATED_AT,'dd-mon-yyyy') 
from tbi, tb, tr 
where 
tbi.id=tb.id and 
tb.id=tr.id 
and 
trunc(tr.updated_at) = to_date('23/02/2016', 'dd/MM/yyyy') 

与您查询的问题(我被它的外观是猜测)你的updated_at格式为DD/MM/YYYY HH24:MI:SS。

因此,23/02/2016不等于23/02/2016 20:00:05。 (A默认HH24:MI:一个日期的ss是00:00:00)

TRUNC()使格式化像日/月/年的时间,并忽略小时

+0

谢谢。这是工作,但为什么没有trunc不工作? – monvic

+0

我已经解释了所有@monvic – sagi

+0

明白了。谢谢@sagi – monvic

0

问题

tr.updated_at = to_date('23/02/2016', 'dd/MM/yyyy') 

回报你只有结果,其中updated_at等于23/02/2016 00:00:00

解决方案

尝试,而不是执行以下操作:

trunc(tr.updated_at) = to_date('23/02/2016', 'dd/MM/yyyy') 

CF trunc function documentation

0
Because updated_at column have the date with minutes and seconds. 
You are trying to fetch records for which updated_at has the value 
23/02/2016 00:00:00 

尝试此所需的输出:

选择tr.x,tbi.y,TO_CHAR(tr.UPDATED_AT, 'DD-MON-YYYY') 从TBI,TB,TR 其中 tbi.id = tb.id和 tb.id = tr.id和 to_char(tr.updated_at,'dd/mm/yyyy')= to_date('23/02/2016','dd/MM/yyyy' )

0

使用TRUNC,正如其他答案所建议的,它使得不可能在此字段上使用索引(基于函数的索引除外)。出于这个原因,你可能更喜欢

tr.updated_at between to_date('23/02/2016', 'dd/mm/yyyy') 
        and to_date('23/02/2016 23:59:59', 'dd/mm/yyyy hh24:mi:ss') 
+0

这个领域没有索引,但很有可能知道未来。谢谢 – monvic