PostgreSQL:如何为时间戳类型的列指定仅具有日期值的WHERE条件?

时间:2017-02-02 07:37:08

标签: sql postgresql

我在PostgreSQL数据库中有一个表,它有一个类型为timestamp的列。现在我需要通过仅指定timestamp列的日期部分来获取所有字段的数据。我怎么能通过SQL查询来做到这一点?

1 个答案:

答案 0 :(得分:2)

将您的专栏投放到date

select ...
from ...
where the_timestamp_column::date = date '2017-01-28';
使用::date

The cast是Postgres特定的语法。如果您更喜欢ANSI SQL,请使用显式cast()

select ...
from ...
where cast(the_timestamp_column as date) = date '2017-01-28';

请注意,上述条件不会使用the_timestamp_column上的索引。如果需要,可以在表达式上创建索引或使用范围查询:

select ...
from ...
where the_timestamp_column >= timestamp '2017-01-28 00:00:00'
  and the_timestamp_column < timestamp '2017-02-01 00:00:00';