1. 程式人生 > >mysql優化一:大資料查詢新增索引

mysql優化一:大資料查詢新增索引

一、索引是什麼?

索引是一種特殊的檔案(InnoDB資料表上的索引是表空間的一個組成部分),它們包含著對資料表裡所有記錄的引用指標。

更通俗的說,資料庫索引好比是一本書前面的目錄,能加快資料庫的查詢速度

二、索引目的

索引的目的在於提高查詢效率

三、索引原理

通過不斷的縮小想要獲得資料的範圍來篩選出最終想要的結果,同時把隨機的事件變成順序的事件,也就是我們總是通過同一種查詢方式來鎖定資料。

四、索引的使用

1、檢視索引

show index from 表名;

2、建立索引

create index 索引名稱 on 表名(欄位名稱(長度))

3、刪除索引:

drop index 索引名 on 表名;

 

五、索引demo:

1、建立測試表test

create table test(
    -> id int not null primary key auto_increment,
    -> name varchar(20)
    -> );

2、插入10萬條語句:

    def insert(self):
        for i in range(1000000):
            self.cursor.execute('insert into test values(0,"this is % d")' % i)
        self.conn.commit()

3、查詢

3.1 開啟執行時間監測:

set profiling=1;

3.2 查詢第1萬條資料

select * from test where title = 'this is  99999';

3.3 檢視執行的時間

show profiles;

3.4 為表title的name欄位建立索引

create index test on test(name(20));

3.5 執行查詢語句

select * from test where name = 'this is  99999';

3.6 再次檢視執行的時間

show profiles;

 

 

 

 

五、查詢方式

1、開啟執行時間監測:

set profiling=1;

2、查詢第一萬條資料ha-99999

select * from test_index where title='ha-99999';

3、檢視