【问题标题】:suitable indexes for where group-by plus plus order-by适用于 where group-by plus plus order-by 的索引
【发布时间】:2013-01-16 21:00:50
【问题描述】:

我有使用 order-by group-by 的查询

选择计数(*),归档2 从 table1 where field1>x group by filed2 order by count(*) desc

什么是这个查询的最佳索引。
我应该单独索引filed1,field2还是一起索引?

【问题讨论】:

标签: mysql indexing group-by sql-order-by


【解决方案1】:

您应该以两种不同的顺序创建两列的索引

ALTER TABLE table1 ADD INDEX field1_field2_ndx (field1,field2);
ALTER TABLE table1 ADD INDEX field2_field1_ndx (field2,field1);

您不应该创建单独的索引,因为使用两列创建索引将导致查询通过索引只是为了满足查询。它永远不需要碰桌子。

即使您创建了单独的索引,查询优化器也会选择两列索引。

现在您有了两个索引,只需相信查询优化器会选择正确的索引。根据查询,EXPLAIN 计划将选择field2_field1_ndx 索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多