【问题标题】:How to properly use index on multiple columns如何在多列上正确使用索引
【发布时间】:2015-08-20 06:00:43
【问题描述】:

我在 PostgreSQL 中有这个查询:

SELECT cte.* 
FROM (

                 select ......
                 from A a
                 left join B b using (id)
                 left join C c on (c.cid=a.cid)
                 left join D d on (d.did=c.did)
                 left join E e on (e.eid=d.eid)
                 left JOIN ( F f
                           JOIN ( SELECT func() AS funcid) x ON f.fid = x.fid) ON a.id = f.id
                 left join G g on (g.gid=c.gid)
                 left join H h on (h.hid=c.hid)
                 where b.userid= first_param 
                 order by .....
) as cte
where cte.issuedate=second_param

此查询使用 2 个参数运行:first_paramINTEGERsecond_paramDATE - 它们都与表 B 的字段相关

此查询会在我的主工作屏幕上生成数据,因此它会被多次使用。

我的困境在于查询的结构,因为 first_paramsecond_param 处于查询的“不同级别”中分别地?此外,second_param 是从公用表表达式而不是直接从 B 访问的

换句话说...选择:

CREATE INDEX name_a
  ON B
  USING btree
  (userid,issuedate);

或者:

CREATE INDEX name_aa
  ON B
  USING btree
  (userid);

CREATE INDEX name_ab
  ON B
  USING btree
  (issuedate);

索引的指导方针说,如果我们多次一起使用 2 列,那么我们应该一起索引它,但在这种情况下我不太确定......

你能建议吗?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    我可能会使用两个单独的索引,它更灵活,并且在大多数情况下性能相同甚至更高。参见例如: 2 PostgreSQL indices on the same column of the same table - redundant?

    例如,我认为在您的查询中,2 列索引对于已发布的比较而言相对无用。

    一般来说,避免使用多列索引,除非您有非常特殊的情况和使用它们的理由。

    【讨论】:

      【解决方案2】:

      你是对的。您应该选择两个单独的索引。如果您使用同一连接中的列(即FROM tableA JOIN tableB ON tableA.columnA1 = tableB.columnB1 AND tableA.columnA2 = tableB.columnB2),您将使用多列索引

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 1970-01-01
        • 2019-04-29
        • 2021-03-06
        • 1970-01-01
        • 2014-08-19
        • 2014-12-16
        • 1970-01-01
        • 2016-08-21
        相关资源
        最近更新 更多