前置条件:

目标库:V4.5.10.3

源库:mysql

问题描述:

执行CREATE INDEX idx_course_006 ON accept.accept_business_course USING btree (

​ trunc(receive_time)

) ; 其中receive_time是timestamp without time zone类型的字段

报错:function trunc(timestamp without time zone) does not exist

原因:瀚高数据库默认情况下不存在trunc(timestampwithout time zone)函数

操作步骤:

使用date_trunc(‘day’,receive_time)

CREATE INDEX idx_course_006 ON accept_business_index USING btree (
date_trunc('day',receive_time)
) ;

预期结果:

索引创建成功

异常处理:

暂未发现相关异常场景

回滚方案:

drop index INDEX idx_course_006;

典型场景示例:

创建 “按日期聚合” 的索引

业务背景

需频繁执行 WHERE trunc(receive_time) = '2024-03-11' 这类按日期过滤的查询,希望通过索引提升性能。

解释

-- 创建索引
CREATE INDEX idx_course_006 ON accept_business_index USING btree (
date_trunc('day',receive_time)
) ;
-- 配套查询(索引可命中)
SELECT *
FROM accept.accept_business_course
WHERE DATE(receive_time) = '2024-03-11';
  • 关键解释:
    • DATE(receive_time):将 timestamp without time zone 类型的字段直接转为 date 类型(自动截断时分秒,等价于 Oracle/MySQL 的 trunc(receive_time));
    • 索引类型选 btree:适合范围查询(如 DATE(receive_time) BETWEEN '2024-03-01' AND '2024-03-10'),是日期类索引的最优选择。