zoukankan      html  css  js  c++  java
  • mysql

    原理:请参考文章: https://www.cnblogs.com/bypp/p/7755307.html

    理论:

    mysql 索引管理
    一、功能
        1、索引的功能就是加速查找
        2、mysql中的primary key,unique,联合唯一也都是索引,这些索引除了加速查找以外,还有约束的功能
    二、mysql的索引分类
        1、普通索引index:加速查找
        2、唯一索引
            主键索引:primary key:加速查找+约束(不能为null且唯一)
            唯一索引:unique:加速查找+约束(唯一,可以为null)
        3、联合索引
            1>、primary key(id, no):联合主键索引
            2>、unique(id, no):联合普通索引
            3>、index(id, no):联合普通索引
        4、全文索引 fulltext:用于搜索很长一篇文章的时候,效果最好
        5、空间索引spatial:了解就好,几乎不用
    三、索引的两大类型hash与btree
        #我们可以在创建上述索引的时候,为其指定索引类型,分两类
            hash类型的索引:查询单条快,范围查询慢
            btree类型的索引:b+树,层数越多,数据量指数级增长(我们就用它,因为innodb默认支持它)
     
        #不同的存储引擎支持的索引类型也不一样
            InnoDB 支持事务,支持行级别锁定,支持 B-tree、Full-text 等索引,不支持 Hash 索引;
            MyISAM 不支持事务,支持表级别锁定,支持 B-tree、Full-text 等索引,不支持 Hash 索引;
            Memory 不支持事务,支持表级别锁定,支持 B-tree、Hash 等索引,不支持 Full-text 索引;
            NDB 支持事务,支持行级别锁定,支持 Hash 索引,不支持 B-tree、Full-text 等索引;
            Archive 不支持事务,支持表级别锁定,不支持 B-tree、Hash、Full-text 等索引;
    四、创建/删除索引的语法【具体将在案例中讲解】
        方法1、创建表时
    	1>普通索引
    		create table tableName
    		(
    			id int unsigned not null,
    			user_name varchar(20) not null,
    			index [indexName] (username(length))
    		);
    	2>唯一索引
    		create table tableName
    		(
    			id int unsigned not null,
    			user_name varchar(16) not null,
    			unique [indexName] (user_name(length))
    		);
        方法2、create在已存在的表上创建索引
    	1>普通索引
    		create index indexName on tableName(columnName);
    		create index indexName on tableName(id, name); #添加普通联合索引
    	2>唯一索引
    		create unique index indexName on tableName(user_name(length));
    	
        方法3、alter table在已存在的表上创建索引
    	1>普通索引
    		alter table tableName add index indexName(columnName);
    	2>唯一索引
    		alter table tableName add unqiue [indexName](user_name(length));
    	3>主键(要确定列不能为null)
    		alter table tableName modify columnName type not null;
    		alter table tableName add primary key(columnName);
    	4>全文索引
    		alter table tableName add fulltext indexName(columnName);
        删除索引:drop index 索引名 on 表名;
    	1>普通索引/唯一索引
    		drop index [indexName] on tableName;
    		alter table tableName drop index indexName;
    	2>主键(删除主键时只需指定PRIMARY KEY,但在删除索引时,你必须知道索引名。)
    		alter table tableName drop primary key;
    五、显示索引信息
    	show index from tableName;
    

      

     

    案例:

    select version();
    -- 5.7.31-log
    
    drop database if exists mysql_study;
    
    create database if not exists mysql_study default charset utf8;
    
    use mysql_study;
    
    drop table if exists employee;
    create table if not exists employee
    (
    	emp_id int unsigned auto_increment,#primary key 可以在这里加
    	emp_name varchar(20) not null,
    	emp_age int not null,
    	emp_no varchar(20),#unique 可以在这里加
    	emp_email varchar(50),
    	create_time datetime default now(),
    	emp_sex tinyint, #index 不可以这样加索引,因为index只是索引,没有约束一说,所以不能在定义字段的时候加索引
    	is_delete tinyint unsigned,
    	primary key(emp_id),
    	unique(emp_no),
    	index(emp_sex)
    )engine = innodb default charset = utf8;
    
    -- create index index_name on employee(emp_email); #添加普通索引 【数据过多时,添加的很慢】
    -- create index index_name on employee(emp_email, emp_age); #添加普通联合索引
    -- create unique unique_name on employee(emp_no); #添加唯一索引
    -- alter table employee add index index_name(emp_email); #修改表结构(添加索引)
    -- drop index index_name on employee; #删除索引
    
    show columns from employee;
    show index from employee;
    
    -- 添加200万+的数据做测试 start
    drop procedure if exists insert_employee_pro;
    delimiter $
    create procedure insert_employee_pro
    (
    	count int
    )
    begin
    	declare i int;
    	declare age tinyint;
    	declare is_delete tinyint;
    	declare sex tinyint;
    	set count = ifnull(count, 100);
    	set i = 1;
    	set age = 20;
    	set is_delete = 0;
    	set sex = 0;
    	while i <= count do
    		insert into employee(emp_name, emp_age, emp_no, emp_email, emp_sex, is_delete) 
    		values(concat('gxy', i), age, concat('gxh', i), concat('gmd', i, '@qq.com'), sex, is_delete);
    		set i = i + 1;
    		set age = age + 1;
    		if age > 40 then
    			set age = 20;
    		end if;
    		if is_delete = 0 then
    			set is_delete = 1;
    		else
    			set is_delete = 0;
    		end if;
    		set sex = sex + 1;
    		if sex > 2 then
    			set sex = 0;
    		end if;
    	end while;
    end;
    $
    delimiter ;
    -- 添加200万+的数据做测试 end
    
    #查看存储过程单个
    show create procedure insert_employee_pro;
    
    call insert_employee_pro(2654321);
    
    -- 测试查询速度
    -- 无索引
    select * from employee where emp_email = 'gmd1239879@qq.com'; #1.673秒很慢
    select * from employee where emp_age > 30 order by emp_age limit 10 offset 100000;#1.918
    
    #加上索引
    #1. 一定是为搜索条件的字段创建索引,比如select * from t1 where age > 5;就需要为age加上索引
    #2. 在表中已经有大量数据的情况下,建索引会很慢,且占用硬盘空间,插入删除更新都很慢,只有查询快,比如create index idx on s1(id); 会扫描表中所有的数据,然后以id为数据项,创建索引结构,存放于硬盘的表中。建完以后,再查询就会很快了
    #3. 需要注意的是:innodb表的索引会存放于s1.ibd文件中,而myisam表的索引则会有单独的索引文件table1.MYI
    
    create index emp_email on employee(emp_email);#创建时间7.131秒
    select * from employee where emp_email = 'gmd1239879@qq.com'; #0.035
    drop index emp_email on employee;
    
    create index emp_age on employee(emp_age);#创建时间4.621
    select * from employee where emp_age > 30 order by emp_age limit 10 offset 100000;#0.862
    drop index emp_age on employee;
    
    
    #正确使用索引
    
    #1、覆盖索引
    #select * from s1 where id=123;
    #该sql命中了索引,但未覆盖索引。
    #利用id=123到索引的数据结构中定位到该id在硬盘中的位置,或者说再数据表中的位置。
    #但是我们select的字段为*,除了id以外还需要其他字段,这就意味着,我们通过索引结构取到id还不够,
    #还需要利用该id再去找到该id所在行的其他字段值,这是需要时间的,很明显,如果我们只select id,就减去了这份苦恼,如下
    #select id from s1 where id=123;
    #这条就是覆盖索引了,命中索引,且从索引的数据结构直接就取到了id在硬盘的地址,速度很快
    
    #2、联合索引
    select * from employee where emp_email = 'gmd1239879@qq.com' and emp_age = 37; #1.528
    create index indexName on employee(emp_email, emp_age);
    select * from employee where emp_email = 'gmd1239879@qq.com' and emp_age = 37; #0.034
    select * from employee where emp_age = 37 limit 1; #1.572
    drop index indexName on employee;
    
    #3、索引合并
    #索引合并:把多个单列索引合并使用
    #分析:
    #组合索引能做到的事情,我们都可以用索引合并去解决,比如
    #create index indexName on employee(emp_email, emp_no);#组合索引
    #我们完全可以单独为 emp_email 和 emp_no 创建索引
    
    #组合索引可以命中:
    #select * from employee where emp_email = 'gmd1239879@qq.com';
    #select * from employee where emp_email = 'gmd1239879@qq.com' and emp_age = 37;
    
    #索引合并可以命中:
    #select * from employee where emp_email = 'gmd1239879@qq.com';
    #select * from employee where emp_age = 37;
    #select * from employee where emp_email = 'gmd1239879@qq.com' and emp_age = 37;
    
    #乍一看好像索引合并更好了:可以命中更多的情况,但其实要分情况去看,如果是name='egon' and email='adf',
    #那么组合索引的效率要高于索引合并,如果是单条件查,那么还是用索引合并比较合理
    
    
    
    #若想利用索引达到预想的提高查询速度的效果,我们在添加索引时,必须遵循以下原则
    #1.最左前缀匹配原则,非常重要的原则,
    #create index ix_name_email on s1(name,email,)
    -- 最左前缀匹配:必须按照从左到右的顺序匹配
    #select * from s1 where name='egon'; #可以
    #select * from s1 where name='egon' and email='asdf'; #可以
    #select * from s1 where email='alex@oldboy.com'; #不可以
    #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的顺序可以任意调整。
    
    #2.=和in可以乱序,比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意顺序,mysql的查询优化器
    #会帮你优化成索引可以识别的形式
    
    #3.尽量选择区分度高的列作为索引,区分度的公式是count(distinct col)/count(*),
    #表示字段不重复的比例,比例越大我们扫描的记录数越少,唯一键的区分度是1,而一些状态、
    #性别字段可能在大数据面前区分度就是0,那可能有人会问,这个比例有什么经验值吗?使用场景不同,
    #这个值也很难确定,一般需要join的字段我们都要求是0.1以上,即平均1条扫描10条记录
    
    #4.索引列不能参与计算,保持列“干净”,比如from_unixtime(create_time) = ’2014-05-29’
    #就不能使用到索引,原因很简单,b+树中存的都是数据表中的字段值,
    #但进行检索时,需要把所有元素都应用函数才能比较,显然成本太大。
    #所以语句应该写成create_time = unix_timestamp(’2014-05-29’);
    
    #最左前缀示范
    #select * from s1 where id>3 and name='egon' and email='alex333@oldboy.com' and gender='male';
    #create index indexName on tableName(id,name,email,gender); #未遵循最左前缀
    #create index indexName on tableName(name,email,gender,id); #遵循最左前缀
    
    #最左前缀匹配
    #index(id,age,email,name)
    #条件中一定要出现id(只要出现id就会提升速度)
    #id
    #id age
    #email id
    #id name
    #email #不行  如果单独这个就不能提升速度了
    
    
    #索引无法命中的情况需要注意:
    #like '%xx'
    #使用函数
        #select * from tb1 where reverse(email) = 'wupeiqi';
    #or
    	#特别的:当or条件中有未建立索引的列才失效,以下会走索引
    		#select * from tb1 where nid = 1 or name = 'seven';
    		#select * from tb1 where nid = 1 or name = 'seven@live.com' and email = 'alex'
    #类型不一致
    	#如果列是字符串类型,传入条件是必须用引号引起来,不然...
    	#select * from tb1 where email = 999;
    #普通索引的不等于不会走索引
    	#!=
    	#特别的:如果是主键,则还是会走索引
    #>
    	#select * from tb1 where email > 'alex'
    	#特别的:如果是主键或索引是整数类型,则还是会走索引
    #排序条件为索引,则select字段必须也是索引字段,否则无法命中
    	#当根据索引排序时候,select查询的字段如果不是索引,则不走索引
    		#select name from s1 order by email desc;不走
    		#select email from s1 order by email desc;走
    	#特别的:如果对主键排序,则还是走索引:
    		#select * from tb1 order by nid desc;
    #组合索引最左前缀
    	#如果组合索引为:(name,email)
    	#name and email       -- 使用索引
    	#name                 -- 使用索引
    	#email                -- 不使用索引
    #count(1)或count(列)代替count(*),注意count(列)的null
    
    #避免使用select *
    #count(1)或count(列) 代替 count(*)
    #创建表时尽量时 char 代替 varchar
    #表的字段顺序固定长度的字段优先
    #组合索引代替多个单列索引(经常使用多个条件查询时)
    #尽量使用短索引
    #使用连接(JOIN)来代替子查询(Sub-Queries)
    #连表时注意条件类型需一致
    #索引散列值(重复少)不适合建索引,例:性别不适合
    
    
    #慢查询优化的基本步骤
    #0.先运行看看是否真的很慢,注意设置 SQL_NO_CACHE
    #1.where条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的where都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高
    #2.explain查看执行计划,是否与1预期一致(从锁定记录较少的表开始查询)
    #3.order by limit 形式的sql语句让排序的表优先查
    #4.了解业务方使用场景
    #5.加索引时参照建索引的几大原则
    #6.观察结果,不符合预期继续从0分析
    

      

  • 相关阅读:
    1343. Fairy Tale
    Codeforces Beta Round #97 (Div. 1)
    URAL1091. Tmutarakan Exams(容斥)
    1141. RSA Attack(RSA)
    hdu4003Find Metal Mineral(树形DP)
    hdu2196 Computer待续
    KMP
    莫比乌斯反演
    配对堆
    bzoj3224Treap
  • 原文地址:https://www.cnblogs.com/gygtech/p/13686402.html
Copyright © 2011-2022 走看看