mysql索引是什么?淺談mysql索引
發表時間:2023-05-29 來源:明輝站整理相關軟件相關文章人氣:
[摘要]本篇文章給大家帶來的內容是mysql索引是什么?淺談mysql索引,讓大家對mysql索引有一個簡單的了解。有一定的參考價值,有需要的朋友可以參考一下,希望對你們有所幫助。一:什么是索引索引本身是一...
本篇文章給大家帶來的內容是mysql索引是什么?淺談mysql索引,讓大家對mysql索引有一個簡單的了解。有一定的參考價值,有需要的朋友可以參考一下,希望對你們有所幫助。
一:什么是索引
索引本身是一個獨立的存儲單位,在該單位里邊有記錄著數據表某個字段和字段對應的物理空間。索引內部有算法支持,可以使查詢速度非�?臁!鞠嚓P視頻教程推薦: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%";//使用索引
4,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中文網其它相關文章!
學習教程快速掌握從入門到精通的SQL知識。