ansheng’s blog!

PostgreSQL 根据 date/datetime 类型查询的几种方式

下面的实例中t_createdatetime类型的,需要转换为date类型,如果你要查询的字段已经是date类型则不需要进行转换.

通过cast函数将datetime类型的字段转换为date类型,从而进行查找

select t_create
from orders
where cast(t_create as date) = current_date;

如上所示的更简便的方法

select t_create
from orders
where t_create::date = current_date;

将要查询的日期通过to_date转换为date类型,然后进行查询

select t_create
from orders
where t_create::date = to_date('2019-08-08', 'YYYY-MM-DD');

通过between指定一个日期范围进行查找

select t_create
from orders
where t_create::date between '2019-08-20' and '2019-08-25';
select t_create
from orders
where t_create > (now() - interval '1 week');