首頁  >  文章  >  資料庫  >  mysql索引是什麼?淺談mysql索引

mysql索引是什麼?淺談mysql索引

青灯夜游
青灯夜游轉載
2018-11-22 15:15:493677瀏覽

本篇文章帶給大家的內容是mysql索引是什麼?淺談mysql索引,讓大家對mysql索引有個簡單的了解。有一定的參考價值,有需要的朋友可以參考一下,希望對你們有幫助。

一:什麼是索引

索引本身是一個獨立的儲存單位,在該單位裡邊有記錄資料表某個字段和場對應的物理空間。索引內部有演算法支持,可以讓查詢速度非常快。 【相關影片教學推薦:mysql教學

#有了索引,我們根據索引為條件進行資料查詢,速度就非常快

  1,索引本身有「演算法」支持,可以快速定位我們要找到的關鍵字(字段)

  2,索引字段物理位址有直接對應,幫助我們快速定位要找到的資訊

一個資料表的全部欄位都可以設定索引

#二,索引類型

1,四種類型:

(1) 主鍵parimary key

必須給主鍵索引設定auto_increment,索引列的值要求不能為null,要唯一

(2)唯一unique index

#索引列的值不能重複,但允許有空值

#(3)普通索引index

索引列的值可以重複。

(4)全文索引fulltext index

Myisam資料表可以設定該索引

2,複合索引

##索引是由兩個或更多的列組成,就稱複合索引或聯合索引。

三,建立索引

#1,建立表格時

1),建立一個member表時,並建立各種索引。

create table member(
  id  int not null auto_increment comment '主键',
  name char(10) not null default '' comment '姓名',
  height tinyint not null default 0 comment '身高',
  old tinyint not null default 0 comment '年龄',
  school varchar(32) not null default '' comment '学校',
  intro text comment '简介',
  primary key (id),  // 主键索引
  unique index nm (name), //唯一索引,索引也可以设置名称,不设置名字的话,默认字段名
  index (height),   //普通索引
  fulltext index (intro) //全文索引
)engine = myisam charset = utf8;

2),為現有資料表新增索引

//注:一般设置主键后,会把主键字段设置为自增。(alter table member  modify id  int not null auto_increment comment '主键';)
alter table member add primary key(id); 
alter table member add unique key nm (name);
alter table member add index(height);
alter table member add fulltext index(intro);

3),建立一個複合索引(索引沒有名稱,預設將第一個欄位取出作為名稱)

alter table member add unique key nm (name,height);

2,刪除索引 

alter table 表名 drop primary key;//删除主键索引

注意:

該主鍵欄位如果存在auto_increment 屬性,需要先刪除。 (alter table 表名modify 主鍵int not null comment '主鍵')去除去資料表欄位的auto_increment屬性;

#

alter table 表名 drop  index 索引名称;  //删除其它索引(唯一,普通,全文)

例:

alter table member drop index nm;

四、explain 查看索引是否使用

#具體操作:

explain 查詢sql語句

這是沒有設定主鍵索引的情形:(執行速度、效率低)

#加上主鍵後:

五、索引適合的場景

1、where查詢條件(where之後設定的查詢條件欄位都適合做索引)。

2、排序查詢(order by欄位)

六、索引原則

1、欄位獨立原則

###
select * from emp where empno = 1325467;//empno条件独立,使用索引
select * from emp where empno+2 = 1325467;//empno条件不独立,只有独立的条件字段才可以使用索引
######2,左原則#########模糊查詢,like & _######    %:關聯多個模糊內容##### ##    _:關聯一個模糊內容######範例:   ###
select * form 表名 where a like "beijing%";//使用索引
select * from 表名 where a like "beijing_";//使用索引
select * from 表名 where a like "%beijing%”;//不使用索引
select * from 表名 where a like "%beijing";//不使用索引
######3,複合索引index(a,b) ### ###
select * from 表名 where a like "beijing%";//使用索引
select * from 表名 where b like "beijing%;//不使用索引
select * form 表名 where a like "beijing%" and b like "beijng%";//使用索引
#####44 ,or原則#########OR左右的關聯條件必須都具備索引,才可以使用索引。 ######例:(index(a)、index(b))   ###
select * from 表名 where a = 1 or b = 1;//使用索引
select * from 表名 where a = 1 or c = 1;//没有使用索引
######總結:###以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。 ###

以上是mysql索引是什麼?淺談mysql索引的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除