我有一个查询的形式:
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/