【问题标题】:Can I have multi-order index for composite/multi-column index in MySQL?我可以在 MySQL 中为复合/多列索引设置多顺序索引吗?
【发布时间】:2021-10-27 04:52:29
【问题描述】:

我有一个像这样的invoices 表:

| id   | client_id | is_recurring |
|----- |-----------| -------------|
| 1    | 2121      | 0            |
| 2    | 7434      | 1            |

现在,在我的整个申请过程中,我可能有以下查询:

select * from invoices where client_id = 2121 and is_recurring = 0;

select * from invoices where is_recurring = 0 and client_id = 2121;

或任何其他的where子句顺序。

我已经分别在 client_id 和 is_recurring 上有了索引。

但是对于复合索引,我应该在上面创建复合索引

compost_index('client_id','is_recurring')

compost_index('is_recurring','client_id')

或两者兼有?

请注意,两者的顺序不同。那么对于不同订单搜索的性能呢?我应该创建具有多个顺序/方向的复合索引吗?

更新: 另外,如果我有一个 date 列,我将使用它来比较更大或更小或排序依据,我应该使用哪些复合索引组合?

【问题讨论】:

    标签: mysql composite-index


    【解决方案1】:

    作为一个粗略的经验法则,通过将限制性更强(基数更高)的列放在首位,您可能会期望在两列索引中获得更好的性能。所以,我建议:

    CREATE INDEX ON invoices compost_index (client_id, is_recurring)
    

    如果使用此索引,MySQL 将仅通过 client_id 过滤而丢弃大部分索引。另一方面,is_recurring 列可能只取 0 和 1 这两个值。因此,按此过滤可能不允许在扫描索引时丢弃许多记录。

    【讨论】:

    【解决方案2】:

    无论在哪里订购;
    任一 INDEX 订单 - 无论基数如何;见proof
    也就是说,either WHEREeither INDEX 处理得同样好。
    不是单列索引 - 它们可能会妨碍您。

    同时,复合索引也处理相应的单列需求。也就是说,INDEX(a,b) 负责处理需要INDEX(a) 的情况,但不处理需要INDEX(b) 的情况。

    为此:

     where client_id = 2121 and is_recurring = 0 and date > '2021-04-28';
    

    使用了新规则:

    INDEX(client_id, is_recurring,  -- in either order
          date)                     -- then the range test
    

    即把所有用=(或IS NULL)测试的列放在前面;那么你就有机会添加一个范围测试。

    where client_id = 2121 and date > '2021-04-28' -- (client_id, date)
    where client_id = 2121 order by date > '2021-04-28'
              -- also (client_id, date), but now the order is required
    where client_id = 2121
      and date > '2021-04-28'
      order by date    -- again (client_id, date), specific ordering
    where client_id = 2121
      and is_recurring = 0
      and date > '2021-04-28';  -- back to the 3-column one above
    

    = 测试是一回事;所有不等式测试都是“范围”。

    更多:http://mysql.rjweb.org/doc.php/index_cookbook_mysql

    【讨论】:

    • 那么对于'b',我还需要声明单个索引吗?还要检查更新的问题
    • @JaberAlNahian - 我想我现在已经回答了你删除的版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2021-05-30
    • 2011-05-14
    • 2019-01-10
    • 2019-09-16
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多