MySQL索引的使用 及簡單介紹索引

MySQL

索引

  • 索引的概念
    • 在關係數據庫中,索引是一種單獨的、物理的對數據庫表中一列或多列的值進行排序的一種存儲結構,它是某個表中一列或若干列值的集合和相應的指向表中物理標識這些值的數據頁的邏輯指針清單。索引的作用相當於圖書的目錄,可以根據目錄中的頁碼快速找到所需的內容。
  • 索引使用場景
    • 適用於日常業務中,查詢佔得比重比較大的操作
索引創建的基本原則
  • 比較頻繁的作爲查詢條件的字段
  • 唯一性太差的字段不適合作爲單獨創建的索引,即使它被頻繁作爲查詢條件
  • 更新頻繁的字段不能作爲索引
  • 不會出現在where子句中的字段不該創建索引

索引實現

採用的結構
  • 搜索樹

    • 搜索樹 (B樹系列)時間複雜度(O(log(n)))
      檢索效率和高度有關
      可以提供有序性
      相比較二叉搜索樹,高度更低
  • 哈希(hash)散列表

    • 哈希(hash)散列表
      檢索率高 時間複雜度(O(1))
      但是無序
索引的幾種形式
* **主鍵      (Primary Key)**
            --   	I
            create table Teacher(
            	id int,
            	name varchar(20),
            	primary key (id);
            
            --		II
            create table Teacher(
            	id int primary key,
            	name varchar(20)--     	III
            
            create table Teacher(
            	id int,
            	name varchar(20),
            --   創建多字段的主鍵
            	primary key (id,name);
            
            --   	IIII  追加主鍵
            create table Teacher(
            	id int,
            	name varchar(20);
            alter table Teacher add primary key(id);

  • 唯一鍵 (Unique)
           create table Teacher(
           	id int primary key,
           	name varchar(20) unique;
           	
           create table Teacher(
           
           	id int primary key,
           	name varchar(20),
           	unique (name);
           	
           -- 追加唯一鍵
           alter table Teacher add unique (name);

  • 普通索引 (Key|Index)
         create table Teacher(
         	id int primary key,
         	name varchar(20),
         	gender varchar(4),
         	unique (name),
         	index (gender);
         
         create table Teacher(
         	id int primary key,
         	name varchar(20),
         	gender varchar(4),
         	unique (name);
         -- 追加
         alter table Teacher add index (gender);
         
         -- 直接創建
         create index idx_gender on                        Teacher(gender);

  • 全文索引 (FULLTEXT
    極少使用
     
      CREATE TABLE articles (
     
     id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
     
     title VARCHAR(200),
     
     body TEXT,
     
     FULLTEXT (title,body)
     
     )engine=MyISAM;
查詢索引
     show keys from Teacher\G;
     
     show index from Teacher\G;
索引的刪除
    alter table Teacher drop primary key;
    
    alter table Teacher drop index  idx_gender;
查看索引是否命中
  • 關鍵字: explain
  • 使用
    explain select * from EMP where deptno = 10\G;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章