date当我尝试使用该函数在 PostgreSQL 中对类型为表字段的表达式创建索引时date_trunc,出现以下错误。
functions in index expression must be marked IMMUTABLE
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
从 StackOverflow 和 Google 的搜索来看,这似乎是一个常见问题。对我来说,问题在于似乎最常见的建议解决方案不起作用。最常见的建议解决方案是将date字段设为timestamp with timezone. 这是一个例子。
create table test (foo date);
create index on test (date_trunc('month', foo at time zone 'GMT'));
Run Code Online (Sandbox Code Playgroud)
据我所知,该create index...声明的形式是普遍建议的解决方案。然而,正如我所说,这不会改变我的结果。我仍然收到上面列出的错误。
顺便说一句,这是 PostgreSQL 版本 9.6.9。
Jas*_*sen 11
唯一date_trunc(text,interval)并且date_trunc(text,timestamp)不可变
create index on test (date_trunc('month', foo::timestamp ));
Run Code Online (Sandbox Code Playgroud)
问题在于 foo at time zone 'GMT'表达式foo at time zone 'GMT'本身并不是不可变的。它不是一成不变的,因为它取决于会话 time zone设置。
令人困惑的at time zone 'GMT'是at time zone 'GMT' ,如果被索引的列是类型timestamptz(带有时区的时间戳 ),那么该操作将修复索引表达式。