简体   繁体   English

我应该使用唯一字段还是非唯一字段开始 MySQL 索引?

[英]Should I begin a MySQL index with unique or non-unique field?

The problem I have is the following:我遇到的问题如下:

  • I have a table that contains about 100000000 rows我有一个包含大约 100000000 行的表
  • it has 22 fields - some numeric, some text它有 22 个字段 - 一些数字,一些文本
  • it has a primary key id (auto-incremented integer)它有一个主键id (自动递增的整数)
  • it has a field another_id of type bigint , and a unique key on it它有一个bigint类型的字段another_id和一个唯一的键
  • it has a field called state that can take only 4 integer values (0 to 3)它有一个名为state的字段,只能取 4 个整数值(0 到 3)
  • I need that the queries of the following form are executed as fast as possible:我需要尽快执行以下形式的查询:
SELECT COUNT(*) 
FROM my_table 
WHERE another_id IN ( <about 100 values> ) 
AND state = ...

for different values of state .对于不同的state值。

How should the index look like?索引应该如何? I was thinking about two options:我在考虑两个选择:

  • KEY another_id:state (another_id, state)
  • KEY state:another_id (state, another_id)

Is there any difference in performance between those two variants?这两种变体之间的性能有什么不同吗? Is there anything else to consider?还有什么要考虑的吗?

Edit: engine is InnoDB编辑:引擎是 InnoDB

For the query you show, you should create the index with state , another_id in that order.对于您显示的查询,您应该按stateanother_id创建索引。

Define the index with any columns referenced in equality conditions first, after them add one column referenced in a range condition or ORDER BY or GROUP BY.首先使用在相等条件中引用的任何列定义索引,然后添加在范围条件或 ORDER BY 或 GROUP BY 中引用的列。

You may also like my answer to Does Order of Fields of Multi-Column Index in MySQL Matter or my presentation How to Design Indexes, Really , or the video .您可能还喜欢我对 MySQL 中多列索引的字段顺序是否重要的​​回答或我的演示如何设计索引,真的,或视频

I agree with the answer above.我同意楼上的回答。 One clarification though is that you want to have ita hash index not btree index.一个澄清虽然是你想要 ita 哈希索引而不是 btree 索引。 It should work faster.它应该工作得更快。 The hash index wouldn't work well with any queries that involve inequality such as <=哈希索引不适用于任何涉及不等式的查询,例如 <=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM