sql - 在 PostgreSQL 中索引空值

标签 sql database postgresql indexing

我有一个查询的形式:

select m.id from mytable m
left outer join othertable o on o.m_id = m.id
    and o.col1 is not null and o.col2 is not null and o.col3 is not null
where o.id is null

查询返回几百条记录,尽管表有数百万行,而且它需要很长时间才能运行(大约一个小时)。

当我使用以下方式检查我的索引统计信息时:

select * from pg_stat_all_indexes
where schemaname <> 'pg_catalog' and (indexrelname like 'othertable_%' or indexrelname like 'mytable_%')

我看到只有 othertable.m_id 的索引被使用,而 col1..3 的索引根本没有被使用。这是为什么?

我在 few places 中读到,PG 传统上无法索引 NULL 值。但是,我读过这据说自 PG 8.3 以来发生了变化?我目前在 Ubuntu 10.04 上使用 PostgreSQL 8.4。我是否需要专门制作一个“部分”或“功能”索引来加速 IS NOT NULL 查询,或者它是否已经在索引 NULL 而我只是误解了这个问题?

最佳答案

你可以试试部分索引:

CREATE INDEX idx_partial ON othertable (m_id)
WHERE (col1 is not null and col2 is not null and col3 is not null);

来自文档:http://www.postgresql.org/docs/current/interactive/indexes-partial.html

关于sql - 在 PostgreSQL 中索引空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3467982/

相关文章:

SQL Server SELECT 最后 N 行

c# - 使用 C# 在 SQL 中使用 UPDATE 命令时出错

php - 将数据库信息显示到 html 表中 Wordpress

c# - 如何更改此 Ext.Net 示例以使用 Sql 而不是 Linq?

sql - 为什么一个简单的 T-SQL UDF 函数会使代码执行速度慢 3 倍

sql - 将带有外键的第三张表的记录复制到另一张表

SQL MAX 函数和字符串

sql - 如何根据 PostgreSQL 中 JSON 中的另一个字符串从 JSON 中查询一个字符串?

postgresql - Postgres - 具有多个 where 子句的索引

mysql - 如何迁移现有记录以匹配 Rails 中的新 ORM