mysql>select * from city where name='wuhan'; mysql>alter table city add index idx_na(name);
mysql>create index idx_name1 on city(name);
删除索引
1
mysql> alter table city drop index idx_na;
覆盖索引(联合索引)
1
Master [world]>alter table city add index idx_co_po(countrycode,population);
前缀索引
1 2
db01 [world]>alter table city add index idx_di(district(5)); 注意:数字列不能用作前缀索引。
唯一索引
1 2
db01 [world]>alter table city add unique index idx_uni1(name); ERROR 1062 (23000): Duplicate entry 'San Jose' for key 'idx_uni1'
统计city表中,以省的名字为分组,统计组的个数
1 2 3 4
select district,count(id) from city group by district; 需求: 找到world下,city表中 name列有重复值的行,最后删掉重复的行 db01 [world]>select name,count(id) as cid from city group by name having cid>1 order by cid desc; db01 [world]>select * from city where name='suzhou';
ALL : 全表扫描,不走索引 例子: 1. 查询条件列,没有索引 SELECT * FROM t_100w WHERE k2='780P'; 2. 查询条件出现以下语句(辅助索引列) USE world DESC city; DESC SELECT * FROM city WHERE countrycode <> 'CHN'; DESC SELECT * FROM city WHERE countrycode NOT IN ('CHN','USA'); DESC SELECT * FROM city WHERE countrycode LIKE '%CH%'; 注意:对于聚集索引列,使用以上语句,依然会走索引 DESC SELECT * FROM city WHERE id <> 10;
索引扫描 index < range < ref < eq_ref < const(system) 从左到右性能依次变好
INDEX : 全索引扫描 1. 查询需要获取整个索引树中的值时: DESC SELECT countrycode FROM city;
2. 联合索引中,任何一个非最左列作为查询条件时: idx_a_b_c(a,b,c) ---> a ab abc
SELECT * FROM t1 WHERE b SELECT * FROM t1 WHERE c
RANGE : 索引范围扫描 辅助索引> < >= <= LIKE IN OR BETWEEN AND 主键 <> NOT IN 例子: 1. DESC SELECT * FROM city WHERE id<5; 2. DESC SELECT * FROM city WHERE countrycode LIKE 'CH%'; 3. DESC SELECT * FROM city WHERE countrycode IN ('CHN','USA'); 注意: 1和2例子中,可以享受到B+树的优势,但是3例子中是不能享受的. 所以,我们可以将3号列子改写: DESC SELECT * FROM city WHERE countrycode='CHN' UNION ALL SELECT * FROM city WHERE countrycode='USA';
ref: 非唯一性索引,等值查询 DESC SELECT * FROM city WHERE countrycode='CHN';
eq_ref: 在多表连接时,非驱动表连接条件使用了唯一索引(uk pK)
DESC SELECT b.name,a.name FROM city AS a JOIN country AS b ON a.countrycode=b.code WHERE a.population <100; DESC country
system,const : 唯一索引的等值查询 DESC SELECT * FROM city WHERE id=10;
全部覆盖: select * from t1 where a= and b= and c= select * from t1 where a in and b in and c in select * from t1 where b= and c= and a= 部分覆盖: select *from t1 where a=and b= select * from t1 where a= select * from t1 where a= and c= select * from t1 where a= and b > < >= <= like and c= select xxxfrom t1 where a order by b 不覆盖: b bc c
key_len的计算:idx(a,b,c)
假设某条查询可以完全覆盖三列联合索引。例如:
1
select * from t1 where a= and b= and c=
key_len=a长度+b长度+c长度
长度指的是什么?
长度受到:数据类型,字符集影响
长度指的是:列的最大储值字节长度
数字:
not null 没有not null
tinyint 1 1+1
int 4 4+1
bigint 8 8+1
字符:utf8 —–> 一个字符最大占3个字节
not null 没有not null
char(10) 3*10 3*10+1
vchar(10) 3*10+2 3*10+2+1
例:
1 2 3 4 5 6 7 8 9 10
create table t1 ( a int not null, b int, c int char(10) not null, d varchar (10) ) charset = utf8mb4 index(a,b,c,d)
extra: filesort ,文件排序. SHOW INDEX FROM city; ALTER TABLE city ADD INDEX CountryCode(CountryCode); ALTER TABLE city DROP INDEX idx_c_p;
DESC SELECT * FROM city WHERE countrycode='CHN' ORDER BY population
ALTER TABLE city ADD INDEX idx_(population); DESC SELECT * FROM city WHERE countrycode='CHN' ORDER BY population ALTER TABLE city ADD INDEX idx_c_p(countrycode,population); ALTER TABLE city DROP INDEX idx_; ALTER TABLE city DROP INDEX CountryCode; DESC SELECT * FROM city WHERE countrycode='CHN' ORDER BY population
结论: 1.当我们看到执行计划extra位置出现filesort,说明由文件排序出现 2.观察需要排序(ORDER BY,GROUP BY ,DISTINCT )的条件,有没有索引 3. 根据子句的执行顺序,去创建联合索引
索引优化效果测试: 优化前: [root@db01 ~]# mysqlslap --defaults-file=/etc/my.cnf \ > --concurrency=100 --iterations=1 --create-schema='oldboy' \ > --query="select * from oldboy.t_100w where k2='780P'" engine=innodb \ > --number-of-queries=2000 -uroot -p123 -verbose mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Running for engine rbose Average number of seconds to run all queries: 701.743 seconds Minimum number of seconds to run all queries: 701.743 seconds Maximum number of seconds to run all queries: 701.743 seconds Number of clients running queries: 100 Average number of queries per client: 20
优化后: [root@db01 ~]# mysqlslap --defaults-file=/etc/my.cnf --concurrency=100 --iterations=1 --create-schema='oldboy' --query="select * from oldboy.t_100w where k2='780P'" engine=innodb --number-of-queries=2000 -uroot -p123 -verbose mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Running for engine rbose Average number of seconds to run all queries: 0.190 seconds Minimum number of seconds to run all queries: 0.190 seconds Maximum number of seconds to run all queries: 0.190 seconds Number of clients running queries: 100 Average number of queries per client: 20
联合索引: 1. SELECT * FROM t1 WHERE a= b= 我们建立联合索引时: ALTER TABLE t1 ADD INDEX idx_a_b(a,b); ALTER TABLE t1 ADD INDEX idx_b_a(b,a); 以上的查询不考虑索引的顺序,优化器会自动调整where的条件顺序 注意: 索引,我们在这种情况下建索引时,需要考虑哪个列的唯一值更多,哪个放在索引左边.
2. 如果出现where 条件中出现不等值查询条件 DESC SELECT * FROM t_100w WHERE num <1000 AND k2='DEEF'; 我们建索引时: ALTER TABLE t_100w ADD INDEX idx_2_n(k2,num); 语句书写时 DESC SELECT * FROM t_100w WHERE k2='DEEF' AND num <1000 ; 3. 如果查询中出现多子句 我们要按照子句的执行顺序进行建立索引.
(1) 必须要有主键,如果没有可以做为主键条件的列,创建无关列 (2) 经常做为where条件列 order by group by join on, distinct 的条件(业务:产品功能+用户行为) (3) 最好使用唯一值多的列作为索引,如果索引列重复值较多,可以考虑使用联合索引 (4) 列值长度较长的索引列,我们建议使用前缀索引. (5) 降低索引条目,一方面不要创建没用索引,不常使用的索引清理,percona toolkit(xxxxx) (6) 索引维护要避开业务繁忙期
不走索引的情况(开发规范)
没有查询条件,或者查询条件没有建立索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
select * from tab; 全表扫描。 select * from tab where 1=1; 在业务数据库中,特别是数据量比较大的表。 是没有全表扫描这种需求。 1、对用户查看是非常痛苦的。 2、对服务器来讲毁灭性的。 (1) select * from tab; SQL改写成以下语句: select * from tab order by price limit 10 ; 需要在price列上建立索引 (2) select * from tab where name='zhangsan' name列没有索引 改: 1、换成有索引的列作为查询条件 2、将name列建立索引
查询结果集是原表中的大部分数据,应该是25%以上
1 2 3 4 5 6 7 8
查询的结果集,超过了总数行数25%,优化器觉得就没有必要走索引了。
假如:tab表 id,name id:1-100w ,id列有(辅助)索引 select * from tab where id>500000; 如果业务允许,可以使用limit控制。 怎么改写 ? 结合业务判断,有没有更好的方式。如果没有更好的改写方案 尽量不要在mysql存放这个数据了。放到redis里面。
这样会导致索引失效. 错误的例子: mysql> alter table tab add index inx_tel(telnum); Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> mysql> desc tab; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | telnum | varchar(20) | YES | MUL | NULL | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.01 sec) mysql> select * from tab where telnum='1333333'; +------+------+---------+ | id | name | telnum | +------+------+---------+ | 1 | a | 1333333 | +------+------+---------+ 1 row in set (0.00 sec) mysql> select * from tab where telnum=1333333; +------+------+---------+ | id | name | telnum | +------+------+---------+ | 1 | a | 1333333 | +------+------+---------+ 1 row in set (0.00 sec) mysql> explain select * from tab where telnum='1333333'; +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+
| 1 | SIMPLE | tab | ref | inx_tel | inx_tel | 63 | const | 1 | Using index condition | +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+ 1 row in set (0.00 sec) mysql> explain select * from tab where telnum=1333333; +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ | 1 | SIMPLE | tab | ALL | inx_tel | NULL | NULL | NULL | 2 | Using where | +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ 1 row in set (0.00 sec) mysql> explain select * from tab where telnum=1555555; +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ | 1 | SIMPLE | tab | ALL | inx_tel | NULL | NULL | NULL | 2 | Using where | +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ 1 row in set (0.00 sec) mysql> explain select * from tab where telnum='1555555'; +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+ | 1 | SIMPLE | tab | ref | inx_tel | inx_tel | 63 | const | 1 | Using index condition | +----+-------------+-------+------+---------------+---------+---------+-------+------+-----------------------+ 1 row in set (0.00 sec) mysql>
<> ,not in 不走索引(辅助索引)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
EXPLAIN SELECT * FROM teltab WHERE telnum <> '110'; EXPLAIN SELECT * FROM teltab WHERE telnum NOT IN ('110','119');
mysql> select * from tab where telnum <> '1555555'; +------+------+---------+ | id | name | telnum | +------+------+---------+ | 1 | a | 1333333 | +------+------+---------+ 1 row in set (0.00 sec) mysql> explain select * from tab where telnum <> '1555555';
单独的>,<,in 有可能走,也有可能不走,和结果集有关,尽量结合业务添加limit or或in 尽量改成union EXPLAIN SELECT * FROM teltab WHERE telnum IN ('110','119'); 改写成: EXPLAIN SELECT * FROM teltab WHERE telnum='110' UNION ALL SELECT * FROM teltab WHERE telnum='119'
like “%_” 百分号在最前面不走
1 2 3
EXPLAIN SELECT * FROM teltab WHERE telnum LIKE '31%' 走range索引扫描 EXPLAIN SELECT * FROM teltab WHERE telnum LIKE '%110' 不走索引 %linux%类的搜索需求,可以使用elasticsearch+mongodb 专门做搜索服务的数据库产品