【问题标题】:Postgres index 2 columns with conditionPostgres索引2列有条件
【发布时间】:2023-03-05 17:34:02
【问题描述】:

给定一个存储表(~10k 记录)和一个时间表表(~200k 记录),我正在尝试创建和索引以供规划器使用,但到目前为止它忽略了它。

select * from stores str
   inner join schedule sch on sch.store_id = str.store_id
where sch.open is true and sch.tables > 0

create index sch_open_tables_idx on schedule(open, tables) where open is true and tables > 0

有正确的方法吗?

【问题讨论】:

  • 能否包含导致您认为索引被忽略以及在哪个查询中被忽略的日志/结果/测试?
  • 请阅读postgresql-performance然后edit您的问题并提供缺失的信息。
  • 至少,您不需要索引中的open 列(它将始终是true),但store_id 可能会有所帮助(作为该索引中的第一列) . -- 另外,您可以在查询和索引中都使用where sch.openis true 不是必需的(但也不会受到伤害,可空性不会改变这里的情况;它只是感觉噪音)。

标签: postgresql indexing postgresql-9.4


【解决方案1】:

你需要的索引是:

create index sch_open_tables_id on schedule(store_id)
where open and tables > 0;

store_id 可能是stores 表上的主键,所以上面已经有一个索引。如果没有:

create index store_id on stores(store_id);

【讨论】:

    【解决方案2】:

    这些是 2 个表,因此使用 2 个索引 - 每个索引一个,反正这样的小表不应该需要部分索引

    EXPLAIN select * from stores str
       inner join schedule sch USING (store_id)
    where sch.open is true and tables > 0;
    
    create index sch_open_idx on schedule(store_id) where open is true;
    create index str_tables_idx on stores(store_id) where tables > 0;
    
    vacuum analyze stores;
    vacuum analyze schedule;
    
    EXPLAIN select * from stores str
       inner join schedule sch USING (store_id)
    where sch.open is true and tables > 0;
    

    【讨论】:

    • 好的,但是为什么你认为tables 列属于stores
    • 列表属于schedule。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多