gpt4 book ai didi

sql - Postgres 在使用 date() 函数时不使用索引

转载 作者:搜寻专家 更新时间:2023-10-30 20:01:46 24 4
gpt4 key购买 nike

我的模式是

CREATE TABLE a (
id BIGINT PRIMARY KEY,
dt TIMESTAMP NOT NULL
);

并且我在 dt 上创建了一个索引:

CREATE INDEX a_dt_index ON a (dt);

当我使用类似这样的查询时,索引工作正常

SELECT *
FROM a
WHERE dt >= '2008-12-30' AND dt < '2008-12-31';

但是,当我使用 date() 函数时,未使用索引。

SELECT *
FROM a
WHERE date(dt) = '2008-12-30'

在我看来,这两个查询在语义上是相同的,那么为什么不使用索引呢?为什么我必须创建一个明确的 date() 索引?

CREATE INDEX a_date_index ON a (date(dt));

最佳答案

您可以阅读以下链接以了解更多关于 indexes and date 的信息.但是 TL;DR

functions are black boxes to the database.

因此

If you use any function in your where clauses, you need to create an explicit index with that function. Database does not understand your semantic equivalency.

类似的情况

 WHERE UPPER(NAME)

不在 NAME 列中使用索引。根据数据库 UPPER 函数与 BLACKBOX 没有区别.替换它。

 WHERE BLACKBOX(NAME)

关于sql - Postgres 在使用 date() 函数时不使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com