zoukankan      html  css  js  c++  java
  • mysql爱之深探测

    第一:函数

    一:内置函数

     MYSQL中提供了很多内置的函数,以下:

    CHAR_LENGTH(str)
            返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。
            对于一个包含五个二字节字符集, LENGTH()返回值为 10, 而CHAR_LENGTH()的返回值为5。
    eg:
    mysql> select char_length('zhang')
        -> ;
    +----------------------+
    | char_length('zhang') |
    +----------------------+
    |                    5 |
    +----------------------+
    1 row in set (0.00 sec)
    
    
    CONCAT(str1,str2,...)
            字符串拼接
            如有任何一个参数为NULL ,则返回值为 NULL。
    
    mysql> select concat('zz','l')
        -> ;
    +------------------+
    | concat('zz','l') |
    +------------------+
    | zzl              |
    +------------------+
    1 row in set (0.01 sec)        
            
            
    CONCAT_WS(separator,str1,str2,...)
            字符串拼接(自定义连接符)
            CONCAT_WS()不会忽略任何空字符串。 (然而会忽略所有的 NULL)。
            
    mysql> select CONCAT_WS('**','zzl','cyy');
    +-----------------------------+
    | CONCAT_WS('**','zzl','cyy') |
    +-----------------------------+
    | zzl**cyy                    |
    +-----------------------------+
    1 row in set (0.00 sec)
            
            
    CONV(N,from_base,to_base)
            进制转换
    
    mysql> SELECT CONV('a',16,2);  表示将 a 由16进制转换为2进制字符串表示
    +----------------+
    | CONV('a',16,2) |
    +----------------+
    | 1010           |
    +----------------+
    1 row in set (0.01 sec)
    
    mysql> SELECT CONV('10',8,2); 表示将 a 由8进制转换为2进制字符串表示
    +----------------+
    | CONV('10',8,2) |
    +----------------+
    | 1000           |
    +----------------+
    1 row in set (0.00 sec)
    
    FORMAT(X,D)
        将数字X 的格式写为'#,###,###.##',以四舍五入的方式保留小数点后 D 位, 并将结果以字符串的形式返回。若  D 为 0, 则返回结果不带有小数点,或不含小数部分。
    
    eg:
    mysql> SELECT FORMAT(89333322.31,5);
    +-----------------------+
    | FORMAT(89333322.31,5) |
    +-----------------------+
    | 89,333,322.31000      |
    +-----------------------+
    1 row in set (0.00 sec)
    
    
    INSERT(str,pos,len,newstr)
            在str的指定位置插入字符串
            pos:要替换位置其实位置
            len:替换的长度
            newstr:新字符串
            特别的:
                如果pos超过原字符串长度,则返回原字符串
                如果len超过原字符串长度,则由新字符串完全替换
    mysql> select insert('zhang','1','1','Z')
        -> ;
    +-----------------------------+
    | insert('zhang','1','1','Z') |
    +-----------------------------+
    | Zhang                       |
    +-----------------------------+
    1 row in set (0.01 sec)
    
    
    INSTR(str,substr)
            返回字符串 str 中子字符串的第一个出现位置。
    
    mysql> select instr('zhang','an')
        -> ;
    +---------------------+
    | instr('zhang','an') |
    +---------------------+
    |                   3 |
    +---------------------+
    1 row in set (0.01 sec)
    
    LEFT(str,len)
            返回字符串str 从开始的len位置的子序列字符。
    
    mysql> select left('zhang',8)
        -> ;
    +-----------------+
    | left('zhang',8) |
    +-----------------+
    | zhang           |
    +-----------------+
    1 row in set (0.00 sec)
    
    mysql> select left('zhang',3);
    +-----------------+
    | left('zhang',3) |
    +-----------------+
    | zha             |
    +-----------------+
    1 row in set (0.00 sec)
    
    LOWER(str)
            变小写
    mysql> select LOWER('ZHAng');
    +----------------+
    | LOWER('ZHAng') |
    +----------------+
    | zhang          |
    +----------------+
    1 row in set (0.00 sec)
    
    
    UPPER(str)
            变大写
    mysql> select UPPER('ZHAng');
    +----------------+
    | UPPER('ZHAng') |
    +----------------+
    | ZHANG          |
    +----------------+
    1 row in set (0.00 sec)        
            
    SUBSTRING(str,pos,len)
            获取字符串子序列
    mysql> select substring('zhang','3','2')
        -> ;
    +----------------------------+
    | substring('zhang','3','2') |
    +----------------------------+
    | an                         |
    +----------------------------+
    1 row in set (0.00 sec)
            
    LOCATE(substr,str,pos)
            获取子序列索引位置
    
    mysql> select locate('f','zhangfddadadafff','1');
    +------------------------------------+
    | locate('f','zhangfddadadafff','1') |
    +------------------------------------+
    |                                  6 |
    +------------------------------------+
    1 row in set (0.00 sec)
    
    REPEAT(str,count)
            返回一个由重复的字符串str 组成的字符串,字符串str的数目等于count 。
            若 count <= 0,则返回一个空字符串。
            若str 或 count 为 NULL,则返回 NULL 。
            
    mysql> select repeat('zhang',3)
        -> ;
    +-------------------+
    | repeat('zhang',3) |
    +-------------------+
    | zhangzhangzhang   |
    +-------------------+
    1 row in set (0.01 sec)
    
    mysql> select repeat('zhang',2)
        -> ;
    +-------------------+
    | repeat('zhang',2) |
    +-------------------+
    | zhangzhang        |
    +-------------------+
    1 row in set (0.00 sec)
    
    
    REPLACE(str,from_str,to_str)
            返回字符串str 以及所有被字符串to_str替代的字符串from_str 。
            
    mysql> select replace('zhangzhanling','ling','zhan')
        -> ;
    +----------------------------------------+
    | replace('zhangzhanling','ling','zhan') |
    +----------------------------------------+
    | zhangzhanzhan                          |
    +----------------------------------------+
    1 row in set (0.00 sec)
            
    REVERSE(str)
            返回字符串 str ,顺序和字符顺序相反。
            
    
    mysql> select reverse('zhang')
        -> ;
    +------------------+
    | reverse('zhang') |
    +------------------+
    | gnahz            |
    +------------------+
    1 row in set (0.01 sec)
    
    RIGHT(str,len)
            从字符串str 开始,返回从后边开始len个字符组成的子序列
    
    mysql> select right('zhang','3')
        -> ;
    +--------------------+
    | right('zhang','3') |
    +--------------------+
    | ang                |
    +--------------------+
    1 row in set (0.00 sec)
    
    SPACE(N)
            返回一个由N空格组成的字符串。
    
    mysql> select space(4)
        -> ;
    +----------+
    | space(4) |
    +----------+
    |          |
    +----------+
    1 row in set (0.00 sec)
            
    
    不带有len 参数的格式从字符串str返回一个子字符串,起始于位置 pos。带有len参数的格式从字符串str返回一个长度同len字符相同的子字符串,起始于位置 pos。 使用 FROM的格式为标准 SQL 语法。也可能对pos使用一个负值。假若这样,则子字符串的位置起始于字符串结尾的pos 字符,而不是字符串的开头位置。在以下格式的函数中可以对pos 使用一个负值。
    SUBSTRING(str,pos) , 
    mysql> SELECT SUBSTRING('zhangzhanling',5);
    +------------------------------+
    | SUBSTRING('zhangzhanling',5) |
    +------------------------------+
    | gzhanling                    |
    +------------------------------+
    1 row in set (0.00 sec)
    
    SUBSTRING(str FROM pos)
    
    mysql> SELECT SUBSTRING('zhangzhanling' from 5);
    +-----------------------------------+
    | SUBSTRING('zhangzhanling' from 5) |
    +-----------------------------------+
    | gzhanling                         |
    +-----------------------------------+
    1 row in set (0.00 sec)
    
    SUBSTRING(str,pos,len) , 
    mysql> SELECT SUBSTRING('zhangzhanling',4,5);
    +--------------------------------+
    | SUBSTRING('zhangzhanling',4,5) |
    +--------------------------------+
    | ngzha                          |
    +--------------------------------+
    1 row in set (0.00 sec)
    
    SUBSTRING(str FROM pos FOR len)
    mysql> SELECT SUBSTRING('zhangzhanling' from -4 for 2);
    +------------------------------------------+
    | SUBSTRING('zhangzhanling' from -4 for 2) |
    +------------------------------------------+
    | li                                       |
    +------------------------------------------+
    1 row in set (0.01 sec)
    View Code

    更多的请参照:

    https://dev.mysql.com/doc/refman/5.7/en/functions.html

     二:自定义函数

    1.查看自定义函数功能是个否开启:

    mysql> show variables like '%func%';
    +---------------------------------+-------+
    | Variable_name                   | Value |
    +---------------------------------+-------+
    | log_bin_trust_function_creators | OFF   |
    +---------------------------------+-------+
    1 row in set, 12 warnings (0.02 sec)
    
    mysql> SET GLOBAL log_bin_trust_function_creators=1; 开启自定义函数功能
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> show variables like '%func%';
    +---------------------------------+-------+
    | Variable_name                   | Value |
    +---------------------------------+-------+
    | log_bin_trust_function_creators | ON    |
    +---------------------------------+-------+
    1 row in set, 12 warnings (0.01 sec)
    
    注:SET GLOBAL log_bin_trust_function_creators=1; 关闭自定义函数功能

    2.基本语法:

      delimiter 自定义符号  -- 如果函数体只有一条语句, begin和end可以省略, 同时delimiter也可以省略
      create function 函数名(形参列表) returns 返回类型  -- 注意是retruns
      begin
        函数体    -- 函数内定义的变量如:set @x = 1; 变量x为全局变量,在函数外面也可以使用
        返回值
      end
      自定义符号
      delimiter ;

    3.创建自定义函数示例:

    mysql> delimiter $$
    mysql> create function my(a int, b int) returns int
        -> begin
        ->     return a + b;
        -> end
        -> $$
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> delimiter ;

    4.删除函数:

    mysql> drop function my;
    Query OK, 0 rows affected (0.02 sec)

    5.执行函数:

    mysql> select my(11,23);
    +-----------+
    | my(11,23) |
    +-----------+
    |        34 |
    +-----------+
    1 row in set (0.01 sec)

    第二:索引

    一:索引介绍

    为什么用索引?
    在我们的生产环境中,一般读(查询)写(插入,更新,删除)的比例能占到1:10甚至更多,因此对查询语句的优化是非常重要的,这里就必须用索引喽。
    索引是什么?
    索引是数据库中专门用于帮助用户快速查询数据的一种数据结构,类似与字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置目录,然后直接获取。
    索引的好处是什么?
    1.索引可以加快查询速度,但是并不是索引越多越好。

    2.mysql中的primary key,unique,联合唯一也都是索引,这些索引除了加速查找以外,还有约束的功能

    如果mysql数据库添加太多的索引,磁盘的iostat磁盘使用率会持续很高,甚至长时间达到100%。

    二:mysql中常见的索引:

    普通索引:

      只有加速查找的功能

    eg:

    创建表 + 索引 
    mysql> create table in1(
        ->     nid int not null auto_increment primary key,
        ->     name varchar(32) not null,
        ->     email varchar(64) not null,
        ->     extra text,
        ->     index ix_name (name)
        -> );
    Query OK, 0 rows affected (0.05 sec)
    
    创建索引
    mysql> create index int_name on in1(nid);
    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查看索引
    mysql> show index from in1;
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | in1   |          0 | PRIMARY  |            1 | nid         | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    | in1   |          1 | ix_name  |            1 | name        | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    | in1   |          1 | int_name |            1 | nid         | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    3 rows in set (0.01 sec)
    
    删除索引
    mysql> drop index int_name on in1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查看是否删除成功
    mysql> show index from in1;
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | in1   |          0 | PRIMARY  |            1 | nid         | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    | in1   |          1 | ix_name  |            1 | name        | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    2 rows in set (0.00 sec)
    
    注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。
    create index ix_extra on in1(extra(32));

    唯一索引:

        主键索引 PRIMARY KEY:加速查找+约束(不为空、不能重复)
        唯一索引 UNIQUE:加速查找+约束(不能重复)

    创建表 
    mysql> create table in2(
        ->     nid int not null auto_increment primary key,
        ->     name varchar(32) not null,
        ->     email varchar(64) not null,
        ->     extra text,
        ->     unique ix_name (name)
        -> );
    Query OK, 0 rows affected (0.03 sec)
    
    创建唯一索引
    mysql> create unique index nid_name on in2(nid);
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    主键索引:

      加速查询 和 唯一约束(不可含null)  

    第一种创建方式:
    mysql> create table in3(
        ->     nid int not null auto_increment primary key,
        ->     name varchar(32) not null,
        ->     email varchar(64) not null,
        ->     extra text,
        ->     index ix_name (name)
        -> );
    Query OK, 0 rows affected (0.03 sec)
    
    第二种创建方式:
    
    mysql> create table in4(
        ->     nid int not null auto_increment,
        ->     name varchar(32) not null,
        ->     email varchar(64) not null,
        ->     extra text,
        ->     primary key(nid),
        ->     index ix_name (name)
        -> );
    Query OK, 0 rows affected (0.03 sec)
    
    删除主键索引
    mysql> alter table in4 modify nid int, drop primary key;
    Query OK, 0 rows affected (0.05 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    增加主键索引
    mysql> alter table in4 add primary key(name);
    Query OK, 0 rows affected (0.05 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    组合索引:

      简单的讲是将n个列组合成一个索引

      PRIMARY KEY(id,name):联合主键索引

      UNIQUE(id,name):联合唯一索引

           INDEX(id,name):联合普通索引

    mysql> create table in5(
        ->     nid int not null auto_increment primary key,
        ->     name varchar(32) not null,
        ->     email varchar(64) not null,
        ->     extra text
        -> );
    
    PRIMARY KEY(id,name):联合主键索引
    mysql> create index ix_name_email on in5(nid,name);
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    UNIQUE(id,name):联合唯一索引
    mysql> alter table in5 add unique index(nid,name);
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    INDEX(id,name):联合普通索引
    mysql> create index ix_name on in5(name,email);
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    第三:测试索引

    一:测试准备数据

    创建表
    mysql> create table s1(
        -> id int,
        -> name varchar(20),
        -> gender char(6),
        -> email varchar(50)
        -> );
    Query OK, 0 rows affected (0.03 sec)
    
    创建存储过程,实现批量插入记录
    mysql> delimiter $$    声明存储过程的结束符号 :$$
    mysql> create procedure auto_insert1()
        -> BEGIN
        ->     declare i int default 1;
        ->     while(i<3000000)do
        ->         insert into s1 values(i,'zzl','man',concat('zzl',i,'@wsdashi.com'));
        ->         set i=i+1;
        ->     end while;
        -> END  #$$结束 
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> delimiter ;重新声明分号为结束符号
    
    查看存储过程
    mysql> show create procedure auto_insert1G
    *************************** 1. row ***************************
               Procedure: auto_insert1
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
        Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `auto_insert1`()
    BEGIN
        declare i int default 1;
        while(i<3000000)do
            insert into s1 values(i,'zzl','man',concat('zzl',i,'@wsdashi.com'));
            set i=i+1;
        end while;
    END
    character_set_client: gbk
    collation_connection: gbk_chinese_ci
      Database Collation: latin1_swedish_ci
    1 row in set (0.00 sec)
    
    调用存储过程
    mysql> call auto_insert1();
    mysql> call auto_insert1();
    Query OK, 1 row affected (6 hours 30 min 52.60 sec)

    二:没有建索引的情况下查询

    mysql> select * from s1 where id=3500000;
    Empty set (1.63 sec)

    时间1.63 sec

    三:已经存在大量数据建索引

    mysql> create index s1_id on s1(id);
    Query OK, 0 rows affected (7.54 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    注:如果在生产环境下面,在已经有的数据中,创建索引的时候,会锁表,用户不能使用该表,所以一般这样的操作要晚上做 

    四:索引建立完成,并且依据刚建立的字段索引查询数据

    mysql> select * from s1 where id=35000000;
    Empty set (0.01 sec)

    时间0.01 sec

     五:小结:

    1. 一定是为搜索条件的字段创建索引,比如select * from s1 where id = 222;就需要为id加上索引,如果id加上索引查询其他的字段是不管用的

    2. 在表中已经有大量数据的情况下,建索引会很慢,且占用硬盘空间,建完后查询速度加快

    注意:在生产环境中,一个新的功能上线,需要建表,站在运维的角度,一定要多问以下开发,这个表是否有大量的读操作,如果有的话,需要开发明确怎么查询的,从而建索引,如果读的少,写的多,可根据情况不建索引,索引过多会消耗磁盘利用率的。

    第四:如何正确命中索引

    一:索引未命中

    1.范围问题:或者说条件不明确,条件中出现这些符号或关键字>、>=、<、<=、!= 、between...and...、like、

    等于:指定要找2000这个id号,在索引树中可以快速的查找
    mysql> select count(*) from s1 where id=2000;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (0.00 sec)
    
    大于:会利用索引树,没有指定那个id,而是指定了一个范围,这个范围包含大于2000的id,则mysql会拿着2001去搜索树中找一次,然后2002在找,一次类推,整体下来,和整表扫描没啥区别
    mysql> select count(*) from s1 where id>2000;
    +----------+
    | count(*) |
    +----------+
    |  2997999 |
    +----------+
    1 row in set (1.21 sec)
    
    如果范围小的话,查询速度仍然是很快的。
    mysql> select count(*) from s1 where id>2000 and id<3000;
    +----------+
    | count(*) |
    +----------+
    |      999 |
    +----------+
    1 row in set (0.01 sec)
    
    不等于:不等于2000,范围很大,查询很慢。
    mysql> select count(*) from s1 where id != 2000;
    +----------+
    | count(*) |
    +----------+
    |  2999998 |
    +----------+
    1 row in set (1.20 sec)
    等于2000,就一个数,则查询很快。
    mysql> select count(*) from s1 where id = 2000;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (0.00 sec)
    
    between ...and...
    范围大的,查询依然还是很慢的
    mysql> select count(*) from s1 where id between 1 and 3000000;
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (1.30 sec)
    
    范围小的,查询是快的
    mysql> select count(*) from s1 where id between 1 and 2;
    +----------+
    | count(*) |
    +----------+
    |        2 |
    +----------+
    1 row in set (0.00 sec)
    
    like:前面带%号查询比后面带%或者等于特定值的要慢
    mysql> select count(*) from s1 where id like '1000dd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (1.09 sec)
    
    mysql> select count(*) from s1 where id like '1000dd%';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (1.08 sec)
    
    mysql> select count(*) from s1 where id like '%1000';
    +----------+
    | count(*) |
    +----------+
    |      300 |
    +----------+
    1 row in set (1.14 sec)

    2.尽量选择区分度高的列作为索引,区分度的公式是count(distinct col)/count(*),表示字段不重复的比例,比例越大我们扫描的记录数越少,唯一键的区分度是1,而一些状态、性别字段可能在大数据面前区分度就是0,这个比例使用场景不同,这个值也很难确定,一般需要join的字段我们都要求是0.1以上,即平均1条扫描10条记录

    查看下表结构
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  | MUL | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.02 sec)
    
    删除id的索引
    mysql> drop index  s1_id on s1;
    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查看下是否删除成功
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  |     | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.00 sec)
    
    查看一个name等于dddd的个数有多少,速度是慢的
    mysql> select count(*) from s1 where name='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (1.77 sec)
    
    创建name的索引
    mysql> create index s1_name on s1(name);
    Query OK, 0 rows affected (8.35 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查询速度明显提升很多
    mysql> select count(*) from s1 where name='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.01 sec)
    
    查询name为zzl的字段,速度再一次变慢
    mysql> select count(*) from s1 where name='zzl';
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (1.05 sec)
    
    为何是这种情况呢?
    
    我们编写存储过程为表s1批量添加记录,name字段的值均为zzl,也就是说name这个字段的区分度很低
    
    利用b+树的结构,查询的速度与树的高度成反比,要想将树的高低控制的很低,
    
    需要保证:在某一层内数据项均是按照从左到右,从小到大的顺序依次排开,即左1<左2<左3<...
    
    而对于区分度低的字段,无法找到大小关系,因为值都是相等的,毫无疑问,还想要用b+树存放这些等值的数据,
    只能增加树的高度,字段的区分度越低,则树的高度越高。极端的情况,索引字段的值都一样,那么b+树几乎成了一根棍。
    本例中就是这种极端的情况,name字段所有的值均为'zzl'
    
    所以得出,为区分度低的字段建立索引,索引树的高度会很高。
    
    1:如果条件是name='dddd',那么肯定是可以第一时间判断出'dddd'是不在索引树中的(因为树中所有的值均为'zzl’),所以查询速度很快
    
    2:如果条件正好是name='zzl',查询时,我们永远无法从树的某个位置得到一个明确的范围,只能往下找,在往下找,在在往下找。。。这与全表扫描的IO次数没有多大区别,所以速度很慢

    3.=和in可以乱序,比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意顺序,mysql的查询优化器会帮你优化成索引可以识别的形式

     

    查看表结构
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  |     | NULL    |       |
    | name   | varchar(20) | YES  | MUL | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.00 sec)

    删除原有的索引
    mysql> drop index s1_name on s1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    确认删除
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  |     | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.00 sec)

    没有建索引之前,查询速度是很慢点
    mysql> select count(*) from s1 where name='zzl' and gender='man' and email='137@wsdashi.com'
        -> ;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (1.73 sec)

    创建联合索引
    mysql> create index s1_name on s1(name,gender,email);
    Query OK, 0 rows affected (15.21 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    查询速度加快
    mysql> select count(*) from s1 where name='zzl' and gender='man' and email='137@wsdashi.com'
        -> ;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)

    随意的还位置,查询速度不变
    mysql> select count(*) from s1 where name='zzl' and email='137@wsdashi.com' and gender='man';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)

    但是如果是两个的话,查询速度是慢的
    mysql> select count(*) from s1 where name='zzl' and email='137@wsdashi.com' ;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (2.00 sec)

    是一个的话,查询速度也是慢的
    mysql> select count(*) from s1 where name='zzl' ;
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (1.91 sec)

    4.索引列不能参与计算,保持列“干净”,比如from_unixtime(create_time) = ’2014-05-29’就不能使用到索引,原因很简单,b+树中存的都是数据表中的字段值,但进行检索时,需要把所有元素都应用函数才能比较,显然成本太大。所以语句应该写成create_time = unix_timestamp(’2014-05-29’)

    查看表结构
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  |     | NULL    |       |
    | name   | varchar(20) | YES  | MUL | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.01 sec)
    
    删除原有的索引
    mysql> drop index s1_name on s1;
    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    创建id索引
    mysql> create index s1_name on s1(id);
    Query OK, 0 rows affected (7.63 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查看表结构
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  | MUL | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.01 sec)
    
    查询id的速度是相当快的,因为id有索引。
    mysql> select count(*) from s1 where id=4000;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (0.00 sec)
    
    索引id字段参与了计算,无法拿到一个明确的值去索引树中查找,所以查询速度是比较慢的
    mysql> select count(*) from s1 where id*2=4000;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (1.02 sec)

    5.and/or

    1、and与or的逻辑
        条件1 and 条件2:所有条件都成立才算成立,但凡要有一个条件不成立则最终结果不成立
        条件1 or 条件2:只要有一个条件成立则最终结果就成立
    
    2、and的工作原理
        条件:
            a = 10 and b = 'ddd' and c > 3 and d =4
        索引:
            制作联合索引(d,a,b,c)
        工作原理:
            对于连续多个and:mysql会按照联合索引,从左到右的顺序找一个区分度高的索引字段(这样便可以快速锁定很小的范围),加速查询,即按照d—>a->b->c的顺序
    
    3、or的工作原理
        条件:
            a = 10 or b = 'ddd' or c > 3 or d =4
        索引:
            制作联合索引(d,a,b,c)
            
        工作原理:
            对于连续多个or:mysql会按照条件的顺序,从左到右依次判断,即a->b->c->d

    eg:

    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  | MUL | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  |     | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.00 sec)
    
    name字段添加索引,但是改字段的区分度比较低
    mysql> create index s1name on s1(name); 
    Query OK, 0 rows affected (9.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    name='ddd'可以很快的从索引树中区分出该字段不存在,因而速度会很快
    mysql> select count(*) from s1 where name='ddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
    
    gender是非索引字段的,但是,name='ddd'不成立的话,就不用管gender的条件了呢,相当于只有name='ddd'速度还是很快的;
    mysql> select count(*) from s1 where name='ddd' and gender='man'
        -> ;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
            
    在左边条件成立但是索引字段的区分度低的情况下(name与gender均属于这种情况),
    会依次往右找到一个区分度高的索引字段,加速查询
    mysql> select count(*) from s1 where name='ddd' and gender='man';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='man';
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (20.95 sec)
    
    mysql> create index s1_gender on s1(gender);
    Query OK, 0 rows affected (11.72 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> select count(*) from s1 where name='zzl' and gender='man';
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (3.74 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='xxx';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.01 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='man';
    +----------+
    | count(*) |
    +----------+
    |  2999999 |
    +----------+
    1 row in set (3.01 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='man' and id=333;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (0.01 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='man' and id>333;
    +----------+
    | count(*) |
    +----------+
    |  2999666 |
    +----------+
    1 row in set (18.17 sec)
    
    mysql> select count(*) from s1 where name='zzl' and gender='xxx' and id>333;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.02 sec)
    
    
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='xxx' and id>222;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
    
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='man' and id>222;
    +----------+
    | count(*) |
    +----------+
    |  2999777 |
    +----------+
    1 row in set (21.25 sec)
    当前面三个条件都成立的时候,都无法用索引达到加速的目的,name和gender是因为区分度低,第三个id因为范围太大了,第四个email的区分度很高,但是没有添加索引,所以该语句查询速度是非常的低的
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='man' and id> 222 and email='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (22.87 sec)
    
    给email字段添加索引
    mysql> create index s1_email on s1(email);
    Query OK, 0 rows affected (16.55 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    添加上email字段的索引后,索引明显的提升
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='man' and id> 222 and email='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.02 sec)
    
    经过分析,在条件为name='zzl' and gender='man' and id>222 and 
    email='dddd'的情况下,我们完全没必要为前三个条件的字段加索引,因为只能用上email字段的索引,
    前三个字段的索引反而会降低我们的查询效率
    
    验证:
    
    
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='man' and id> 222 and email='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.02 sec)
    
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  | MUL | NULL    |       |
    | name   | varchar(20) | YES  | MUL | NULL    |       |
    | gender | char(6)     | YES  | MUL | NULL    |       |
    | email  | varchar(50) | YES  | MUL | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.01 sec)
    
    
    mysql> drop index s1_gender on s1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> drop index s1name on s1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> drop index s1_name on s1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field  | Type        | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id     | int(11)     | YES  |     | NULL    |       |
    | name   | varchar(20) | YES  |     | NULL    |       |
    | gender | char(6)     | YES  |     | NULL    |       |
    | email  | varchar(50) | YES  | MUL | NULL    |       |
    +--------+-------------+------+-----+---------+-------+
    4 rows in set (0.01 sec)
    
    mysql> select count(*) from s1 where name='zzl' and
        -> gender='man' and id> 222 and email='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
    
    删掉索引后时间是0.00不删是0.02,同时也论证了不是索引越多越好的哦

    6. 最左前缀匹配原则

    对于组合索引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的顺序可以任意调整。

    mysql> drop index s1_email on s1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    建立索引的时候,没有将范围写到最后面,查询速度慢
    mysql> create index ddd on s1(id,name,gender,email);
    Query OK, 0 rows affected (16.29 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> select count(*) from s1 where name='zzl' and gender='man' and id > 222  and email='dddd';
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (2.27 sec)
    
    更改查询的位置,有些许的提升,但是提升不大
    mysql> select count(*) from s1 where name='zzl' and gender='man' and email='dddd' and id>222;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (2.10 sec)
    
    删除刚才的索引
    mysql> drop index ddd on s1;
    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    把查询范围的,放到最后
    mysql> create index ddd on s1(name,gender,email,id);
    Query OK, 0 rows affected (17.44 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    查询速度显著提升
    mysql> select count(*) from s1 where name='zzl' and gender='man' and email='dddd' and id>222;
    +----------+
    | count(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.01 sec)

    7.其他

    - 使用函数
        select * from s1 where reverse(email) = '123@wsdashi.com';
                
    - 类型不一致
        如果列是字符串类型,传入条件是必须用引号引起来,不然...
        select * from s1 where email = 999;
        
    #排序条件为索引,则select字段必须也是索引字段,否则无法命中
    - order by
        select name from s1 order by email desc;
        当根据索引排序时候,select查询的字段如果不是索引,则速度仍然很慢
        select email from s1 order by email desc;
        特别的:如果对主键排序,则还是速度很快:
            select * from s1 order by nid desc;
     
    - 组合索引最左前缀
        如果组合索引为:(name,email)
        name and email       -- 命中索引
        name                 -- 命中索引
        email                -- 未命中索引
    
    
    - count(1)或count(列)代替count(*)在mysql中没有差别了
    
    - create index xxxx  on tb(title(19)) #text类型,必须制定长度
    View Code

    二:其他注意的地方

    1 避免使用select *
    2 count(1)或count(列) 代替 count(*)
    3 创建表时尽量时 char 代替 varchar
    4 表的字段顺序固定长度的字段优先
    5 组合索引代替多个单列索引(经常使用多个条件查询时)
    6 尽量使用短索引
    7 使用连接(JOIN)来代替子查询(Sub-Queries)
    8 连表时注意条件类型需一致
    9 索引散列值(重复少)不适合建索引,例:性别不适合

    第五:详谈组合索引和覆盖索引

    一:组合索引

    组合索引时指对表上的多个列合起来做一个索引。组合索引的创建方法与单个索引的创建方法一样,不同之处在仅在于有多个索引列,如下

    mysql> create table s2(
        -> a int,
        -> b int,
        -> primary key(a),
        -> key id_a_b(a,b)
        -> );
    Query OK, 0 rows affected (0.04 sec)

     那么何时需要使用组合索引呢?在讨论这个问题之前,先来看一下组合索引内部的结果。从本质上来说,组合索引就是一棵B+树,不同的是组合索引的键值得数量不是1,而是>=2。接着来讨论两个整型列组成的组合索引,假定两个键值得名称分别为a、b如图

    可以看到这与我们之前看到的单个键的B+树并没有什么不同,键值都是排序的,通过叶子结点可以逻辑上顺序地读出所有数据,就上面的例子来说,即(1,1),(1,2),(2,1),(2,4),(3,1),(3,2),数据按(a,b)的顺序进行了存放。

    因此,对于查询select * from table where a=xxx and b=xxx, 显然是可以使用(a,b) 这个联合索引的,对于单个列a的查询select * from table where a=xxx,也是可以使用(a,b)这个索引的。

    但对于b列的查询select * from table where b=xxx,则不可以使用(a,b) 索引,其实你不难发现原因,叶子节点上b的值为1、2、1、4、1、2显然不是排序的,因此对于b列的查询使用不到(a,b) 索引

    组合索引的第二个好处是在第一个键相同的情况下,已经对第二个键进行了排序处理,例如在很多情况下应用程序都需要查询某个用户的购物情况,并按照时间进行排序,最后取出最近三次的购买记录,这时使用组合索引可以帮我们避免多一次的排序操作,因为索引本身在叶子节点已经排序了,如下

    准备数据表
    mysql> create table buy_log(
        ->     userid int unsigned not null,
        ->     buy_date date
        -> );
    Query OK, 0 rows affected (0.03 sec)
    
    mysql>
    mysql> insert into buy_log values
        -> (1,'2009-01-01'),
        -> (2,'2009-01-01'),
        -> (3,'2009-01-01'),
        -> (1,'2009-02-01'),
        -> (3,'2009-02-01'),
        -> (1,'2009-03-01'),
        -> (1,'2009-04-01');
    Query OK, 7 rows affected (0.00 sec)
    Records: 7  Duplicates: 0  Warnings: 0
    
    mysql>
    mysql> alter table buy_log add key(userid);
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> alter table buy_log add key(userid,buy_date);
    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql>  show create table buy_log;
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Table   | Create Table                                                                                                                                                                                            |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | buy_log | CREATE TABLE `buy_log` (
      `userid` int(10) unsigned NOT NULL,
      `buy_date` date DEFAULT NULL,
      KEY `userid` (`userid`),
      KEY `userid_2` (`userid`,`buy_date`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    1 row in set (0.01 sec)
    
    可以看到possible_keys在这里有两个索引可以用,分别是单个索引userid与联合索引userid_2,但是优化器最终选择了使用的key是userid因为该索引的叶子节点包含单个键值,所以理论上一个页能存放的记录应该更多
    mysql> explain select * from buy_log where userid=2;
    +----+-------------+---------+------------+------+-----------------+--------+---------+-------+------+----------+-------+
    | id | select_type | table   | partitions | type | possible_keys   | key    | key_len | ref   | rows | filtered | Extra |
    +----+-------------+---------+------------+------+-----------------+--------+---------+-------+------+----------+-------+
    |  1 | SIMPLE      | buy_log | NULL       | ref  | userid,userid_2 | userid | 4       | const |    1 |   100.00 | NULL  |
    +----+-------------+---------+------------+------+-----------------+--------+---------+-------+------+----------+-------+
    1 row in set, 1 warning (0.01 sec)
    
    假定要取出userid为1的最近3次的购买记录,用的就是联合索引userid_2了,因为在这个索引中,在userid=1的情况下,buy_date都已经排序好了
    mysql> explain select * from buy_log where userid=1 order by buy_date desc limit 3;
    +----+-------------+---------+------------+------+-----------------+----------+---------+-------+------+----------+--------------------------+
    | id | select_type | table   | partitions | type | possible_keys   | key      | key_len | ref   | rows | filtered | Extra                    |
    +----+-------------+---------+------------+------+-----------------+----------+---------+-------+------+----------+--------------------------+
    |  1 | SIMPLE      | buy_log | NULL       | ref  | userid,userid_2 | userid_2 | 4       | const |    4 |   100.00 | Using where; Using index |
    +----+-------------+---------+------------+------+-----------------+----------+---------+-------+------+----------+--------------------------+
    1 row in set, 1 warning (0.00 sec)
    View Code

    二:覆盖索引

    InnoDB存储引擎支持覆盖索引(covering index,或称索引覆盖),即从辅助索引中就可以得到查询记录,而不需要查询聚集索引中的记录。
    使用覆盖索引的一个好处是:辅助索引不包含整行记录的所有信息,故其大小要远小于聚集索引,因此可以减少大量的IO操作
    注意:覆盖索引技术最早是在InnoDB Plugin中完成并实现,这意味着对于InnoDB版本小于1.0的,或者MySQL数据库版本为5.0以下的,InnoDB存储引擎不支持覆盖索引特性

    对于InnoDB存储引擎的辅助索引而言,由于其包含了主键信息,因此其叶子节点存放的数据为(primary key1,priamey key2,...,key1,key2,...)eg:
    select age from s1 where id=123 and name = 'zzl'; #id字段有索引,但是name字段没有索引,该sql命中了索引,但未覆盖,需要去聚集索引中再查找详细信息。
    重要的是:索引字段覆盖了所有,那全程通过索引来加速查询以及获取结果就ok了
    mysql> desc s1;
    +--------+-------------+------+-----+---------+-------+
    | Field | Type | Null | Key | Default | Extra |
    +--------+-------------+------+-----+---------+-------+
    | id | int(11) | NO | | NULL | |
    | name | varchar(20) | YES | | NULL | |
    | gender | char(6) | YES | | NULL | |
    | email | varchar(50) | YES | | NULL | |
    +--------+-------------+------+-----+---------+-------+
    rows in set (0.21 sec)
    
    mysql> explain select name from s1 where id=1000; #没有任何索引
    +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
    | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
    +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
    | 1 | SIMPLE | s1 | NULL | ALL | NULL | NULL | NULL | NULL | 2688336 | 10.00 | Using where |
    +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
    row in set, 1 warning (0.00 sec)
    
    mysql> create index idx_id on s1(id); #创建索引
    Query OK, 0 rows affected (4.16 sec)
    Records: 0 Duplicates: 0 Warnings: 0
    
    mysql> explain select name from s1 where id=1000; #命中辅助索引,但是未覆盖索引,还需要从聚集索引中查找name
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
    | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
    | 1 | SIMPLE | s1 | NULL | ref | idx_id | idx_id | 4 | const | 1 | 100.00 | NULL |
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
    row in set, 1 warning (0.08 sec)
    
    mysql> explain select id from s1 where id=1000; #在辅助索引中就找到了全部信息,Using index代表覆盖索引
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
    | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
    | 1 | SIMPLE | s1 | NULL | ref | idx_id | idx_id | 4 | const | 1 | 100.00 | Using index |
    +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
    row in set, 1 warning (0.03 sec)
    View Code
    innodb存储引擎并不会选择通过查询聚集索引来进行统计。由于buy_log表有辅助索引,而辅助索引远小于聚集索引,选择辅助索引可以减少IO操作,故优化器的选择如上key为userid辅助索引
    对于(a,b)形式的联合索引,一般是不可以选择b中所谓的查询条件。但如果是统计操作,并且是覆盖索引,则优化器还是会选择使用该索引,如下
    #联合索引userid_2(userid,buy_date),一般情况,我们按照buy_date是无法使用该索引的,但特殊情况下:查询语句是统计操作,且是覆盖索引,则按照buy_date当做查询条件时,也可以使用该联合索引
    mysql> explain select count(*) from buy_log where buy_date >= '2011-01-01' and buy_date < '2011-02-01';
    +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+
    | id | select_type | table   | type  | possible_keys | key      | key_len | ref  | rows | Extra                    |
    +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+
    |  1 | SIMPLE      | buy_log | index | NULL          | userid_2 | 8       | NULL |    7 | Using where; Using index |
    +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+
    1 row in set (0.00 sec)
    View Code

    第六:执行计划

    详细的参考:https://dev.mysql.com/doc/refman/5.5/en/explain-output.html
    
    执行计划:一般情况下是这样的
        all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const
        id,email
        
        慢:
            select * from userinfo3 where name='alex'
            
            explain select * from userinfo3 where name='alex'
            type: ALL(全表扫描)
                select * from userinfo3 limit 1;
        快:
            select * from userinfo3 where email='alex'
            type: const(走索引)

    第七:MySQL慢查询

    一:慢查询优化的基本步骤

    1.如果运行真的是非常的慢,需要设置SQL_NO_CACHE
    2.where条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的where都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高
    3.explain查看执行计划,是否与1预期一致(从锁定记录较少的表开始查询)
    4.order by limit 形式的sql语句让排序的表优先查
    5.了解业务方使用场景
    6.加索引时参照建索引的几大原则
    7.观察结果,不符合预期继续从0分析

    二:慢日志管理

            慢日志
                - 执行时间 > 10
                - 未命中索引
                - 日志文件路径
                
            配置:
                - 内存
                    show variables like '%query%';
                    show variables like '%queries%';
                    set global 变量名 =- 配置文件
                    mysqld --defaults-file='E:xunyoumysql-5.7.16-winx64mysql-5.7.16-winx64my-default.ini'
                    
                    my.conf内容:
                        slow_query_log = ON
                        slow_query_log_file = D:/....
                        
                    注意:修改配置文件之后,需要重启服务
    MySQL日志管理
    ========================================================
    错误日志: 记录 MySQL 服务器启动、关闭及运行错误等信息
    二进制日志: 又称binlog日志,以二进制文件的方式记录数据库中除 SELECT 以外的操作
    查询日志: 记录查询的信息
    慢查询日志: 记录执行时间超过指定时间的操作
    中继日志: 备库将主库的二进制日志复制到自己的中继日志中,从而在本地进行重放
    通用日志: 审计哪个账号、在哪个时段、做了哪些事件
    事务日志或称redo日志: 记录Innodb事务相关的如事务执行时间、检查点等
    ========================================================
    一、bin-log
    1. 启用
    # vim /etc/my.cnf
    [mysqld]
    log-bin[=dir[filename]]
    # service mysqld restart
    2. 暂停
    //仅当前会话
    SET SQL_LOG_BIN=0;
    SET SQL_LOG_BIN=1;
    3. 查看
    查看全部:
    # mysqlbinlog mysql.000002
    按时间:
    # mysqlbinlog mysql.000002 --start-datetime="2012-12-05 10:02:56"
    # mysqlbinlog mysql.000002 --stop-datetime="2012-12-05 11:02:54"
    # mysqlbinlog mysql.000002 --start-datetime="2012-12-05 10:02:56" --stop-datetime="2012-12-05 11:02:54" 
    
    按字节数:
    # mysqlbinlog mysql.000002 --start-position=260
    # mysqlbinlog mysql.000002 --stop-position=260
    # mysqlbinlog mysql.000002 --start-position=260 --stop-position=930
    4. 截断bin-log(产生新的bin-log文件)
    a. 重启mysql服务器
    b. # mysql -uroot -p123 -e 'flush logs'
    5. 删除bin-log文件
    # mysql -uroot -p123 -e 'reset master' 
    
    
    二、查询日志
    启用通用查询日志
    # vim /etc/my.cnf
    [mysqld]
    log[=dir[filename]]
    # service mysqld restart
    
    三、慢查询日志
    启用慢查询日志
    # vim /etc/my.cnf
    [mysqld]
    log-slow-queries[=dir[filename]]
    long_query_time=n
    # service mysqld restart
    MySQL 5.6:
    slow-query-log=1
    slow-query-log-file=slow.log
    long_query_time=3
    查看慢查询日志
    测试:BENCHMARK(count,expr)
    SELECT BENCHMARK(50000000,2*3);
    mysql日志相关管理
  • 相关阅读:
    2019-2020-1 20191312《信息安全专业导论》第十二周学习总结
    GPG
    2019-2020-1 20191312《信息安全专业导论》第十一周学习总结
    wireshark
    ssh
    Nmap
    2019-2020-1 《python程序设计》20192428魏来 综合实践报告
    20192428 魏来 2019-2020《Python程序设计》 实验三 报告
    20192428 实验二《Python程序设计》实验报告
    20192428 实验一《Python程序设计》实验报告
  • 原文地址:https://www.cnblogs.com/ylqh/p/8494524.html
Copyright © 2011-2022 走看看