使用date_trunc创建Postgresql索引

3
关于这个 问题 ,我想创建一个索引以返回与此查询相同的输出。
--takes 2005-10-12
select date_trunc('month',table_withdates.dateoftransfer::date)::Date
from table_withdates;
--returns 2005-10-01

以下内容可以索引,但会返回带有时间戳的日期,这不是我想要的。最初的回答:

下面的内容可以被索引,但会在日期后添加时间戳,这不符合我的要求。

create index on table_withdates  (date_trunc('month', dateoftransfer::timestamp));
--returns 2005-10-01 00:00:00

是否可能创建一个索引,在不使用时间戳的情况下以该格式返回日期?

最初的回答:


谢谢,但是当我运行select date_trunc('month',table_withdates.dateoftransfer::date) from table_withdates;时,它返回2005-10-01 00:00:00+01这个索引会是什么? - mapping dom
dateoftransfer is type date - mapping dom
1个回答

4

手册摘录

返回值的类型是时间戳或间隔,所有比所选字段不重要的字段都设置为零

因此,您需要将 date_trunc 的结果转换为日期:

create index on table_withdates  (date_trunc('month', dateoftransfer)::date);

请注意,为了使索引可用于查询,您需要使用完全相同的表达式,例如:
where date_trunc('month', dateoftransfer)::date  = ...

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