我在Mysql中有下表(T):
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| first | varchar(50) | NO | PRI | NULL | |
| second | varchar(50) | NO | PRI | NULL | |
| third | varchar(50) | NO | PRI | NULL | |
| count | bigint(20) | NO | | NULL | |
+--------+-------------+------+-----+---------+-------+
此表包含数百万行。我创建了以下索引:
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| T | 0 | PRIMARY | 1 | first | A | 591956 | NULL | NULL | | BTREE | | |
| T | 0 | PRIMARY | 2 | second | A | 67927032 | NULL | NULL | | BTREE | | |
| T | 0 | PRIMARY | 3 | third | A | 271708128 | NULL | NULL | | BTREE | | |
| T | 1 | SECONDARY | 1 | second | A | 398399 | NULL | NULL | | BTREE | | |
| T | 1 | SECONDARY | 2 | third | A | 45284688 | NULL | NULL | | BTREE | | |
| T | 1 | SEC | 1 | second | A | 4382389 | NULL | NULL | | BTREE | | |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
搜索类型:
SELECT * FROM T WHERE first = "WHAT" AND third = "EVER";
和
SELECT * FROM T WHERE first = "WHAT" AND second = "EVER";
通常也很快(结果总是在1秒内获得)。然而,搜索如下:
SELECT * FROM T WHERE second = "WHAT" AND third = "EVER";
非常慢(通常超过1分钟)。我创建了索引SEC(参见索引表),但这并没有改善结果。
我应该使用什么索引来加快搜索速度? (我没有继续进行实验,因为创建一个索引需要大约5个小时)
更多信息:该表是静态的(即我不会再添加任何行 - 我只对搜索速度感兴趣),并且磁盘空间不是问题。
答案 0 :(得分:0)
使用包含与您的查询匹配的字段的其他索引。如果行组合是唯一的,则使用主索引。这些提供比二级索引更快的访问。 由于表是静态的 - 索引数不会影响性能(任何更新,删除和插入都需要更新表的每个索引)。
因此,为了更快地从此查询中检索,请创建second
和third
列的索引:
ALTER TABLE T ADD PRIMARY KEY (second, third);