Postgres where子句比较时间戳。

133

我有一个表,其中一列的数据类型是timestamp

其中包含了同一天的多条记录,我想选择所有与那一天相符的行

我应该如何操作?

1个回答

231
假设您实际上是指 timestamp ,因为Postgres中没有 datetime
将时间戳列转换为日期,这将删除时间部分:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

这将返回7月15日以后的所有行。

请注意,上述查询不会使用the_timestamp_column的索引。如果性能很重要,您需要在该表达式上创建一个索引或使用范围条件:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

2
希望我在向大型表提交第一个样式查询之前读了第二部分... - Palace Chan
3
你可以直接比较时间戳和日期字符串。Postgres会自动为你进行类型转换。where the_timestamp_column >= '2015-07-15' and the_timestamp_column < '2015-07-16' - moveson
我用了 "select * from the_table where the_timestamp_column::date = date '2015-07-15';",成功了。谢谢。 - Rajkumar M
转换日期“2015-07-15”不是必需的! - Gaurav
你可以使用DATE(the_timestamp_column)函数。 选择* from the_table where DATE(the_timestamp_column)= date '2015-07-15'; - ibyanik
@İbrahimYANIK:这与我的第一个条件/查询相同。 - user330315

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接