sql新增索引

2021-10-06 21:08:29 字數 2326 閱讀 5076

使用create 語句建立索引

建立組合索引

create

index index_name on

table_name

(column_name,column_name)

include

(score)

普通索引

create

clustered

index index_name on

table_name

(column_name)

;

clustered:表示要建立的索引時聚簇索引,即索引項的順序與表中記錄的物理順序一致的索引組織。

非空索引

create

unique

index index_name on table_name (column_name)

;

主鍵索引

create

table

primary_key

(id int

unsigned comment '無符號'

primary

key auto_increment,

name

varchar(32

)not

null default ' '

);

create

primary

keyindex index_name on table_name (column_name)

;

使用alter table語句建立索引

##1.新增primary key(主鍵索引)

alter table `table_name` add primary key

(`column`)

;##2.新增unique(唯一索引)

alter table `table_name` add

unique

(`column`)

;##3.新增普通索引

alter table `table_name` add index index_name

(`column`)

;##4.新增全文索引

alter table `table_name` add

fulltext

(`column`)

;##5.新增多列索引

alter table `table_name` add index index_name

(`column1`,`column2`,`column3`)

;

刪除索引

drop index index_name on table_name ;

alter table table_name drop index index_name ;

alter table table_name drop primary key ;

注當使用like時,%在前時,索引失效

select id from  t where col like 'mich%'

;-- 這個查詢將使用索引,

select id from t where col like '%like'

;--這個查詢不會使用索引。

注 聯合索引失效條件

不在索引列上做任何操作(計算、函式、(自動or手動)型別轉換),會導致索引失效而轉向全表掃瞄 儲存引擎不能使用索引範圍條件右邊的列

盡量使用覆蓋索引(只訪問索引的查詢(索引列和查詢列一致)),減少select *

mysql在使用不等於(!=或者<>)的時候無法使用索引會導致全表掃瞄

is null,is not null也無法使用索引

ike以萬用字元開頭(』%abc…』)mysql索引失效會變成全表掃瞄的操作。問題:解決like『%字串%』時索引不被使用的方法?

## 字串不加單引號會使索引失效

select *

from staffs where name=

'2000'

;-- 因為mysql會在底層對其進行隱式的型別轉換

select *

from staffs where name=

2000;--

- 未使用索引

sql 新增索引強大

以前沒有親自新增過索引,今天新增了一下,果真強大。幾百倍的速度提公升。select from tbl sys menu m where m.sid in select mr.menu sid from tbl sys mrole mr where mr.role sid in select ur.r...

sql語句新增 修改字段以及索引

在工作中,我們經常會遇到資料庫表字段不夠,修改擴充套件或者修改。修改欄位名 alter table table name rename column a to b 修改字段型別 版本 alter table table name alter column column name column typ...

為SQL表新增全文索引範例

範例 為hr job中的jobtitle,jobdes建立全文索引 execute sp fulltext catalog boli188 create 建立全文目錄,boli188為目錄名.create unique index jobid on hr job jobid 定義唯一的索引,必須是主...