mysql> show index from smw_ids;
+---------+------------+-------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+---------+------------+-------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+
| smw_ids | 0 | PRIMARY | 1 | smw_id | A | 724678 | NULL | NULL | | BTREE | |
| smw_ids | 1 | smw_title | 1 | smw_title | A | 724678 | NULL | NULL | | BTREE | |
| smw_ids | 1 | smw_title | 2 | smw_namespace | A | 724678 | NULL | NULL | | BTREE | |
| smw_ids | 1 | smw_title | 3 | smw_iw | A | 724678 | NULL | NULL | YES | BTREE | |
| smw_ids | 1 | smw_sortkey | 1 | smw_sortkey | A | 724678 | NULL | NULL | | BTREE | |
+---------+------------+-------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+
5 rows in set (0.00 sec)mysql>mysql> explain SELECT smw_title FROM `smw_ids` WHERE smw_namespace=4000;
+----+-------------+---------+-------+---------------+-----------+---------+------+--------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+-----------+---------+------+--------+--------------------------+
| 1 | SIMPLE | smw_ids | index | NULL | smw_title | 296 | NULL | 724678 | Using where; Using index |
+----+-------------+---------+-------+---------------+-----------+---------+------+--------+--------------------------+
1 row in set (0.00 sec)mysql>
smw_namespace在复合索引的中间位置,按理说是怎么样也用不到这个索引才对。为什么KEY里却还有这个复合索引呢?
=4000的只有200多行,实际上它还是进行了全表扫描,没有用到索引。Using index 和KEY里的提示不知道怎么样解释。
a b
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
2 5
3 1
3 2
3 3
3 4这种情况下去找 where b=2 ,然后可以使用这个BTREE索引,MYSQL只需要在每个不同的A中利用直接查找B=2就可以了。
这个例子在《数据库系统概论(第四版)》 王珊 萨师煊 高等教育出版社 (掌握基础知识和概念)
有论述。
版主举的这个例子,它索引查询的时候,还是要全表扫描所有行,才能得到B=2的是哪些行呀。
B-TREE里的索引顺序是从树干往树枝排列的,查询时如果按照树干往树枝走,那么可以用到索引,如果从树枝开始,那么是索引是用不到的吧。2楼:row=724678,和表总数基本相同,在这里判断的。
索引都是已经排好序的。这个原则忘记了。我的问题里,smw_namespace也是排好序的,扫描的时候可以直接定位到smw_namespace不同值的开始和结束。4楼的这个列子把让彻底明白了。