最左边当然很重要,但下面显示在 col1,col3 搜索的情况下,索引 IS 使用了一个点,然后 where 接管,如在explain 输出中看到
create table t1
( id int auto_increment primary key, -- for sanity sake for tweaks
col1 int not null,
col2 int not null,
col3 int not null,
key (col1,col2,col3)
);
-- 我只是在存储过程中运行它以生成足够的行以使任何索引都有用
-- 表示mysql不会在小表上使用索引,稍后参考
运行几百次:
insert t1 (col1,col2,col3) values (rand()*1000,rand()*1000,rand()*1000);
好的,现在我们有足够的数据。下面的第三个显示使用了索引,直到一个点(那个点是col1),然后恢复一个where找到col3
explain select id from t1 where col1=7 and col2=9;
+----+-------------+-------+------+---------------+------+---------+-------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+-------------+------+-------------+
| 1 | SIMPLE | t1 | ref | col1 | col1 | 8 | const,const | 1 | Using index |
+----+-------------+-------+------+---------------+------+---------+-------------+------+-------------+
explain select id from t1 where col1=7 and col2=9 and col3=8;
+----+-------------+-------+------+---------------+------+---------+-------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+-------------------+------+-------------+
| 1 | SIMPLE | t1 | ref | col1 | col1 | 12 | const,const,const | 1 | Using index |
+----+-------------+-------+------+---------------+------+---------+-------------------+------+-------------+
explain select id from t1 where col1=7 and col3=8;
+----+-------------+-------+------+---------------+------+---------+-------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+-------+------+--------------------------+
| 1 | SIMPLE | t1 | ref | col1 | col1 | 4 | const | 1 | Using where; Using index |
+----+-------------+-------+------+---------------+------+---------+-------+------+--------------------------+
外卖
在 col1,col3 搜索中,技术上 (col1,col2,col3) 组合是通过 col1 使用的