mysql爱之深探测

时间:2023-03-09 22:42:35
mysql爱之深探测

第一:函数

一:内置函数

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

CHAR_LENGTH(str)
返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。
对于一个包含五个二字节字符集, LENGTH()返回值为 , 而CHAR_LENGTH()的返回值为5。
eg:
mysql> select char_length('zhang')
-> ;
+----------------------+
| char_length('zhang') |
+----------------------+
| |
+----------------------+
row in set (0.00 sec) CONCAT(str1,str2,...)
字符串拼接
如有任何一个参数为NULL ,则返回值为 NULL。 mysql> select concat('zz','l')
-> ;
+------------------+
| concat('zz','l') |
+------------------+
| zzl |
+------------------+
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 |
+-----------------------------+
row in set (0.00 sec) CONV(N,from_base,to_base)
进制转换 mysql> SELECT CONV('a',,); 表示将 a 由16进制转换为2进制字符串表示
+----------------+
| CONV('a',,) |
+----------------+
| |
+----------------+
row in set (0.01 sec) mysql> SELECT CONV('',,); 表示将 a 由8进制转换为2进制字符串表示
+----------------+
| CONV('',,) |
+----------------+
| |
+----------------+
row in set (0.00 sec) FORMAT(X,D)
将数字X 的格式写为'#,###,###.##',以四舍五入的方式保留小数点后 D 位, 并将结果以字符串的形式返回。若 D 为 , 则返回结果不带有小数点,或不含小数部分。 eg:
mysql> SELECT FORMAT(89333322.31,);
+-----------------------+
| FORMAT(89333322.31,) |
+-----------------------+
| ,,322.31000 |
+-----------------------+
row in set (0.00 sec) INSERT(str,pos,len,newstr)
在str的指定位置插入字符串
pos:要替换位置其实位置
len:替换的长度
newstr:新字符串
特别的:
如果pos超过原字符串长度,则返回原字符串
如果len超过原字符串长度,则由新字符串完全替换
mysql> select insert('zhang','','','Z')
-> ;
+-----------------------------+
| insert('zhang','','','Z') |
+-----------------------------+
| Zhang |
+-----------------------------+
row in set (0.01 sec) INSTR(str,substr)
返回字符串 str 中子字符串的第一个出现位置。 mysql> select instr('zhang','an')
-> ;
+---------------------+
| instr('zhang','an') |
+---------------------+
| |
+---------------------+
row in set (0.01 sec) LEFT(str,len)
返回字符串str 从开始的len位置的子序列字符。 mysql> select left('zhang',)
-> ;
+-----------------+
| left('zhang',) |
+-----------------+
| zhang |
+-----------------+
row in set (0.00 sec) mysql> select left('zhang',);
+-----------------+
| left('zhang',) |
+-----------------+
| zha |
+-----------------+
row in set (0.00 sec) LOWER(str)
变小写
mysql> select LOWER('ZHAng');
+----------------+
| LOWER('ZHAng') |
+----------------+
| zhang |
+----------------+
row in set (0.00 sec) UPPER(str)
变大写
mysql> select UPPER('ZHAng');
+----------------+
| UPPER('ZHAng') |
+----------------+
| ZHANG |
+----------------+
row in set (0.00 sec) SUBSTRING(str,pos,len)
获取字符串子序列
mysql> select substring('zhang','','')
-> ;
+----------------------------+
| substring('zhang','','') |
+----------------------------+
| an |
+----------------------------+
row in set (0.00 sec) LOCATE(substr,str,pos)
获取子序列索引位置 mysql> select locate('f','zhangfddadadafff','');
+------------------------------------+
| locate('f','zhangfddadadafff','') |
+------------------------------------+
| |
+------------------------------------+
row in set (0.00 sec) REPEAT(str,count)
返回一个由重复的字符串str 组成的字符串,字符串str的数目等于count 。
若 count <= ,则返回一个空字符串。
若str 或 count 为 NULL,则返回 NULL 。 mysql> select repeat('zhang',)
-> ;
+-------------------+
| repeat('zhang',) |
+-------------------+
| zhangzhangzhang |
+-------------------+
row in set (0.01 sec) mysql> select repeat('zhang',)
-> ;
+-------------------+
| repeat('zhang',) |
+-------------------+
| zhangzhang |
+-------------------+
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 |
+----------------------------------------+
row in set (0.00 sec) REVERSE(str)
返回字符串 str ,顺序和字符顺序相反。 mysql> select reverse('zhang')
-> ;
+------------------+
| reverse('zhang') |
+------------------+
| gnahz |
+------------------+
row in set (0.01 sec) RIGHT(str,len)
从字符串str 开始,返回从后边开始len个字符组成的子序列 mysql> select right('zhang','')
-> ;
+--------------------+
| right('zhang','') |
+--------------------+
| ang |
+--------------------+
row in set (0.00 sec) SPACE(N)
返回一个由N空格组成的字符串。 mysql> select space()
-> ;
+----------+
| space() |
+----------+
| |
+----------+
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',);
+------------------------------+
| SUBSTRING('zhangzhanling',) |
+------------------------------+
| gzhanling |
+------------------------------+
row in set (0.00 sec) SUBSTRING(str FROM pos) mysql> SELECT SUBSTRING('zhangzhanling' from );
+-----------------------------------+
| SUBSTRING('zhangzhanling' from ) |
+-----------------------------------+
| gzhanling |
+-----------------------------------+
row in set (0.00 sec) SUBSTRING(str,pos,len) ,
mysql> SELECT SUBSTRING('zhangzhanling',,);
+--------------------------------+
| SUBSTRING('zhangzhanling',,) |
+--------------------------------+
| ngzha |
+--------------------------------+
row in set (0.00 sec) SUBSTRING(str FROM pos FOR len)
mysql> SELECT SUBSTRING('zhangzhanling' from - for );
+------------------------------------------+
| SUBSTRING('zhangzhanling' from - for ) |
+------------------------------------------+
| li |
+------------------------------------------+
row in set (0.01 sec)

更多的请参照:

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

2.基本语法:

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

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

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

4.删除函数:

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

5.执行函数:

mysql> select my(,);
+-----------+
| my(,) |
+-----------+
| |
+-----------+
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() not null,
-> email varchar() not null,
-> extra text,
-> index ix_name (name)
-> );
Query OK, rows affected (0.05 sec) 创建索引
mysql> create index int_name on in1(nid);
Query OK, rows affected (0.04 sec)
Records: Duplicates: Warnings: 查看索引
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 | | PRIMARY | | nid | A | | NULL | NULL | | BTREE | | |
| in1 | | ix_name | | name | A | | NULL | NULL | | BTREE | | |
| in1 | | int_name | | nid | A | | NULL | NULL | | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
rows in set (0.01 sec) 删除索引
mysql> drop index int_name on in1;
Query OK, rows affected (0.02 sec)
Records: Duplicates: Warnings: 查看是否删除成功
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 | | PRIMARY | | nid | A | | NULL | NULL | | BTREE | | |
| in1 | | ix_name | | name | A | | NULL | NULL | | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
rows in set (0.00 sec) 注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。
create index ix_extra on in1(extra());

唯一索引:

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

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

主键索引:

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

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

组合索引:

  简单的讲是将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() not null,
-> email varchar() not null,
-> extra text
-> ); PRIMARY KEY(id,name):联合主键索引
mysql> create index ix_name_email on in5(nid,name);
Query OK, rows affected (0.02 sec)
Records: Duplicates: Warnings: UNIQUE(id,name):联合唯一索引
mysql> alter table in5 add unique index(nid,name);
Query OK, rows affected (0.02 sec)
Records: Duplicates: Warnings: INDEX(id,name):联合普通索引
mysql> create index ix_name on in5(name,email);
Query OK, rows affected (0.02 sec)
Records: Duplicates: Warnings:

第三:测试索引

一:测试准备数据

创建表
mysql> create table s1(
-> id int,
-> name varchar(),
-> gender char(),
-> email varchar()
-> );
Query OK, rows affected (0.03 sec) 创建存储过程,实现批量插入记录
mysql> delimiter $$ 声明存储过程的结束符号 :$$
mysql> create procedure auto_insert1()
-> BEGIN
-> declare i int default ;
-> while(i<)do
-> insert into s1 values(i,'zzl','man',concat('zzl',i,'@wsdashi.com'));
-> set i=i+;
-> end while;
-> END #$$结束
Query OK, rows affected (0.01 sec) mysql> delimiter ;重新声明分号为结束符号 查看存储过程
mysql> show create procedure auto_insert1\G
*************************** . 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 ;
while(i<)do
insert into s1 values(i,'zzl','man',concat('zzl',i,'@wsdashi.com'));
set i=i+;
end while;
END
character_set_client: gbk
collation_connection: gbk_chinese_ci
Database Collation: latin1_swedish_ci
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=;
Empty set (1.63 sec)

时间1.63 sec

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

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

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

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

mysql> select * from s1 where id=;
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=;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.00 sec) 大于:会利用索引树,没有指定那个id,而是指定了一个范围,这个范围包含大于2000的id,则mysql会拿着2001去搜索树中找一次,然后2002在找,一次类推,整体下来,和整表扫描没啥区别
mysql> select count(*) from s1 where id>;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.21 sec) 如果范围小的话,查询速度仍然是很快的。
mysql> select count(*) from s1 where id> and id<;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.01 sec) 不等于:不等于2000,范围很大,查询很慢。
mysql> select count(*) from s1 where id != ;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.20 sec)
等于2000,就一个数,则查询很快。
mysql> select count(*) from s1 where id = ;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.00 sec) between ...and...
范围大的,查询依然还是很慢的
mysql> select count(*) from s1 where id between and ;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.30 sec) 范围小的,查询是快的
mysql> select count(*) from s1 where id between and ;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.00 sec) like:前面带%号查询比后面带%或者等于特定值的要慢
mysql> select count(*) from s1 where id like '1000dd';
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.09 sec) mysql> select count(*) from s1 where id like '1000dd%';
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.08 sec) mysql> select count(*) from s1 where id like '%1000';
+----------+
| count(*) |
+----------+
| |
+----------+
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() | YES | MUL | NULL | |
| name | varchar() | YES | | NULL | |
| gender | char() | YES | | NULL | |
| email | varchar() | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
rows in set (0.02 sec) 删除id的索引
mysql> drop index s1_id on s1;
Query OK, rows affected (0.03 sec)
Records: Duplicates: Warnings: 查看下是否删除成功
mysql> desc s1;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int() | YES | | NULL | |
| name | varchar() | YES | | NULL | |
| gender | char() | YES | | NULL | |
| email | varchar() | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
rows in set (0.00 sec) 查看一个name等于dddd的个数有多少,速度是慢的
mysql> select count(*) from s1 where name='dddd';
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.77 sec) 创建name的索引
mysql> create index s1_name on s1(name);
Query OK, rows affected (8.35 sec)
Records: Duplicates: Warnings: 查询速度明显提升很多
mysql> select count(*) from s1 where name='dddd';
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.01 sec) 查询name为zzl的字段,速度再一次变慢
mysql> select count(*) from s1 where name='zzl';
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.05 sec) 为何是这种情况呢? 我们编写存储过程为表s1批量添加记录,name字段的值均为zzl,也就是说name这个字段的区分度很低 利用b+树的结构,查询的速度与树的高度成反比,要想将树的高低控制的很低, 需要保证:在某一层内数据项均是按照从左到右,从小到大的顺序依次排开,即左1<左2<左3<... 而对于区分度低的字段,无法找到大小关系,因为值都是相等的,毫无疑问,还想要用b+树存放这些等值的数据,
只能增加树的高度,字段的区分度越低,则树的高度越高。极端的情况,索引字段的值都一样,那么b+树几乎成了一根棍。
本例中就是这种极端的情况,name字段所有的值均为'zzl' 所以得出,为区分度低的字段建立索引,索引树的高度会很高。 :如果条件是name='dddd',那么肯定是可以第一时间判断出'dddd'是不在索引树中的(因为树中所有的值均为'zzl’),所以查询速度很快 :如果条件正好是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() | YES | | NULL | |
| name | varchar() | YES | MUL | NULL | |
| gender | char() | YES | | NULL | |
| email | varchar() | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
rows in set (0.01 sec) 删除原有的索引
mysql> drop index s1_name on s1;
Query OK, rows affected (0.03 sec)
Records: Duplicates: Warnings: 创建id索引
mysql> create index s1_name on s1(id);
Query OK, rows affected (7.63 sec)
Records: Duplicates: Warnings: 查看表结构
mysql> desc s1;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int() | YES | MUL | NULL | |
| name | varchar() | YES | | NULL | |
| gender | char() | YES | | NULL | |
| email | varchar() | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
rows in set (0.01 sec) 查询id的速度是相当快的,因为id有索引。
mysql> select count(*) from s1 where id=;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (0.00 sec) 索引id字段参与了计算,无法拿到一个明确的值去索引树中查找,所以查询速度是比较慢的
mysql> select count(*) from s1 where id*=;
+----------+
| count(*) |
+----------+
| |
+----------+
row in set (1.02 sec)

5.and/or

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

eg:

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

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

7.其他

- 使用函数
select * from s1 where reverse(email) = '123@wsdashi.com'; - 类型不一致
如果列是字符串类型,传入条件是必须用引号引起来,不然...
select * from s1 where email = ; #排序条件为索引,则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()或count(列)代替count(*)在mysql中没有差别了 - create index xxxx on tb(title()) #text类型,必须制定长度

二:其他注意的地方

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

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

一:组合索引

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

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

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

mysql爱之深探测

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

二:覆盖索引

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= and name = 'zzl'; #id字段有索引,但是name字段没有索引,该sql命中了索引,但未覆盖,需要去聚集索引中再查找详细信息。
重要的是:索引字段覆盖了所有,那全程通过索引来加速查询以及获取结果就ok了
mysql> desc s1;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int() | NO | | NULL | |
| name | varchar() | YES | | NULL | |
| gender | char() | YES | | NULL | |
| email | varchar() | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
rows in set (0.21 sec) mysql> explain select name from s1 where id=; #没有任何索引
+----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| | SIMPLE | s1 | NULL | ALL | NULL | NULL | NULL | NULL | | 10.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+
row in set, warning (0.00 sec) mysql> create index idx_id on s1(id); #创建索引
Query OK, rows affected (4.16 sec)
Records: Duplicates: Warnings: mysql> explain select name from s1 where id=; #命中辅助索引,但是未覆盖索引,还需要从聚集索引中查找name
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
| | SIMPLE | s1 | NULL | ref | idx_id | idx_id | | const | | 100.00 | NULL |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+
row in set, warning (0.08 sec) mysql> explain select id from s1 where id=; #在辅助索引中就找到了全部信息,Using index代表覆盖索引
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
| | SIMPLE | s1 | NULL | ref | idx_id | idx_id | | const | | 100.00 | Using index |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
row in set, warning (0.03 sec)
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 |
+----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+
| | SIMPLE | buy_log | index | NULL | userid_2 | | NULL | | Using where; Using index |
+----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+
row in set (0.00 sec)

第六:执行计划

详细的参考: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 ;
快:
select * from userinfo3 where email='alex'
type: const(走索引)

第七:MySQL慢查询

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

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

二:慢日志管理

        慢日志
- 执行时间 >
- 未命中索引
- 日志文件路径 配置:
- 内存
show variables like '%query%';
show variables like '%queries%';
set global 变量名 = 值
- 配置文件
mysqld --defaults-file='E:\xunyou\mysql-5.7.16-winx64\mysql-5.7.16-winx64\my-default.ini' my.conf内容:
slow_query_log = ON
slow_query_log_file = D:/.... 注意:修改配置文件之后,需要重启服务
MySQL日志管理
========================================================
错误日志: 记录 MySQL 服务器启动、关闭及运行错误等信息
二进制日志: 又称binlog日志,以二进制文件的方式记录数据库中除 SELECT 以外的操作
查询日志: 记录查询的信息
慢查询日志: 记录执行时间超过指定时间的操作
中继日志: 备库将主库的二进制日志复制到自己的中继日志中,从而在本地进行重放
通用日志: 审计哪个账号、在哪个时段、做了哪些事件
事务日志或称redo日志: 记录Innodb事务相关的如事务执行时间、检查点等
========================================================
一、bin-log
. 启用
# vim /etc/my.cnf
[mysqld]
log-bin[=dir\[filename]]
# service mysqld restart
. 暂停
//仅当前会话
SET SQL_LOG_BIN=;
SET SQL_LOG_BIN=;
. 查看
查看全部:
# mysqlbinlog mysql.
按时间:
# mysqlbinlog mysql. --start-datetime="2012-12-05 10:02:56"
# mysqlbinlog mysql. --stop-datetime="2012-12-05 11:02:54"
# mysqlbinlog mysql. --start-datetime="2012-12-05 10:02:56" --stop-datetime="2012-12-05 11:02:54" 按字节数:
# mysqlbinlog mysql. --start-position=
# mysqlbinlog mysql. --stop-position=
# mysqlbinlog mysql. --start-position= --stop-position=
. 截断bin-log(产生新的bin-log文件)
a. 重启mysql服务器
b. # mysql -uroot -p123 -e 'flush logs'
. 删除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=
slow-query-log-file=slow.log
long_query_time=
查看慢查询日志
测试:BENCHMARK(count,expr)
SELECT BENCHMARK(,*);

mysql日志相关管理