索引是一種特殊的文件(innoDB數(shù)據(jù)表上的索引是表空間的一個組成部分)
數(shù)據(jù)量大經常查詢需要建立索引
索引可以加快數(shù)據(jù)庫運行速度
創(chuàng)建測試表
use TCL
create table text_index(title varchar(10));
插入十萬條數(shù)據(jù)
from pymysql import connect
def main():
? ? #創(chuàng)建Connection連接
? ? conn = connect(host = 'localhost',port = 3306,user = 'root' ,password = 'hezhuang',database = 'TCL',charset = 'utf8')
? ? #? 獲得Cursor對象
? ? cursor = conn.cursor()
? ? #插入十萬條數(shù)據(jù)
? ? for? i? in range(100000):
? ? ? ? corsor.execute("insert into text_index values('ha-%d')"%i)
? ? #提交數(shù)據(jù)
? ? conn.commit()
if __name__ == '__main__':
? ? main()
查詢索引
開啟運行時間監(jiān)測? set profiling = 1;
查看第一萬條數(shù)據(jù)ha-9999? ? select * from test_index where title = 'ha-9999';
查看執(zhí)行時間? show profiles;
為表title_index 的title 列創(chuàng)建索引? create index title_index on test_index (title(10));
執(zhí)行查詢語句? select * from test_index where title = 'ha-9999';
再次查看執(zhí)行時間 show profiles;
創(chuàng)建索引的情況
1、主鍵自動建立唯一索引
2、操作的文件使用頻繁可以作為查詢條件的字段應該創(chuàng)建索引
3、查詢中與其他表關聯(lián)的字段,外鍵關系建立索引
4、頻繁更新的字段不適合建立索引,因為每次更新不單單是更新了記錄還會更新索引
5、WHERE條件里用不到的字段不創(chuàng)建索引
6、查詢中排序的字段,排序的字段若通過索引去訪問將大大提高排序速度
7、查詢中統(tǒng)計或者分組字段
不需要創(chuàng)建索引的情況
1、表記錄太少
2、經常增刪改的表
3、如果某個數(shù)據(jù)列包含許多重復內容,為它建立索引就沒有太大的實際效果