mysql愛之深探測

第一:函數

一:內置函數

 MYSQL中提供了不少內置的函數,如下:html

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

更多的請參照:mysql

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

 二:自定義函數

1.查看自定義函數功能是個否開啓:ios

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.基本語法:sql

  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.刪除函數:vim

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%。ide

二: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_insert1\G
*************************** 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的值爲一、二、一、四、一、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:\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事務相關的如事務執行時間、檢查點等
========================================================
1、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' 


2、查詢日誌
啓用通用查詢日誌
# vim /etc/my.cnf
[mysqld]
log[=dir\[filename]]
# service mysqld restart

3、慢查詢日誌
啓用慢查詢日誌
# 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日誌相關管理
相關文章
相關標籤/搜索