SQL 建索引的几大原则: 最左前缀匹配原则,非常重要的原则,mysql会一直向右匹配直到遇到范围查询(>.<.between.like)就停止匹配,比如a = 1 and b = 2 and c > 3 and d = 4 如果建立(a,b,c,d)顺序的索引,d是用不到索引的,如果建立(a,b,d,c)的索引则都可以用到,a,b,d的顺序可以任意调整. =和in可以乱序,比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意顺序,mysql的查询
索引失效的场景: 1.没有 where 条件 直接看 SQL 语句 2.where 条件中所在的列没有建立索引 show index from t; 3.从表中取得数据超过某个阈值.通常认为是 20~30%,即使 where 条件和索引都满足,也不会走索引 看表的行数.看下索引列的 cardinality 值,card 值只能直观反映 = 操作符返回的行数. 对于>=.<=.like.between and 的情况,card 值不能直观判断返回值的数据量. 有时候可以尝试着执行一下,但
mysql 演示数据库:http://downloads.mysql.com/docs/sakila-db.zip 以%开头的LIKE查询不能够利用B-tree索引 explain select * from actor where last_name like '%NI%'\G; explain select * from actor where last_name like 'NI%'\G; 解决办法 先扫描索引 last_name获取满足条件的%NI%的主键actor_id列表,之后根据主
mysql 演示数据库:http://downloads.mysql.com/docs/sakila-db.zip 匹配全值 explain select * from rental where rental_date='2005-05-25 17:22:10' and inventory_id=373 and customer_id=343 匹配值的范围查询 explain select * from rental where customer_id >= 373 and customer_i