在postgresql(windows 9.2.4版)中比较日期时,我遇到了一个奇怪的情况。
我的表中有一列,名为update_date,类型为'timestamp without timezone‘。
客户端可以在此字段中仅搜索日期(即: 2013-05-03)或带时间的日期(即: 2013-05-03 12:20:00)。
此列的值为当前所有行的timestamp,日期部分相同(2013-05-03),但时间部分不同。
当我比较这一列时,我得到了不同的结果。如下所示:
select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date < '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-04' -> results found
select * from table where update_date >= '2013-05-03' -> results found
我的问题是,我如何才能使第一个查询能够得到结果,我的意思是为什么第三个查询可以工作,而第一个查询不能工作?
发布于 2013-10-20 02:45:56
@Nicolai关于强制转换以及为什么条件对于任何数据都是假的是正确的。我猜您更喜欢第一种形式,因为您希望避免对输入字符串进行日期操作,对吗?你不需要害怕:
SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);
发布于 2013-10-20 01:58:25
当您比较update_date >= '2013-05-03'
postgres时,会将值强制转换为相同类型的值以进行比较。所以你的'2013-05-03‘被转换为'2013-05-03 00:00:00’。
因此,对于update_date = '2013-05-03 14:45:00‘,您的表达式将是:
'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'
这始终是false
要解决此问题,请将update_date转换为date
select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result
发布于 2013-10-20 02:41:38
使用range
类型。如果用户输入日期:
select *
from table
where
update_date
<@
tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');
如果用户输入时间戳,则不需要::date + 1
部分
http://www.postgresql.org/docs/9.2/static/rangetypes.html
http://www.postgresql.org/docs/9.2/static/functions-range.html
https://stackoverflow.com/questions/19469154
复制相似问题