為mysql資料庫建立索引

2021-06-05 18:02:35 字數 1976 閱讀 7204

建立和刪除索引

索引的建立可以在create table語句中進行,也可以單獨用create index或alter table來給表增加索引。刪除索引可以利用alter table或drop index語句來實現。

(1)使用alter table語句建立索引。

語法如下:

alter table table_name add index index_name (column_list) ;

alter table table_name add unique (column_list) ;

alter table table_name add primary key (column_list) ;

其中包括普通索引、unique索引和primary key索引3種建立索引的格式,table_name是要增加索引的表名,column_list指出對哪些列進行索引,多列時各列之間用逗號分隔。索引名index_name可選,預設時,mysql將根據第乙個索引列賦乙個名稱。另外,alter table允許在單個語句中更改多個表,因此可以同時建立多個索引。

建立索引的示例如下:

mysql> use tpsc

database changed

mysql> alter table tpsc add index shili (tpmc ) ;

query ok, 2 rows affected (0.08 sec)

records: 2 duplicates: 0 warnings: 0

(2)使用create index語句對錶增加索引。

能夠增加普通索引和unique索引兩種。其格式如下:

create index index_name on table_name (column_list) ;

create unique index index_name on table_name (column_list) ;

說明:table_name、index_name和column_list具有與alter table語句中相同的含義,索引名不可選。另外,不能用create index語句建立primary key索引。

(3)刪除索引。

刪除索引可以使用alter table或drop index語句來實現。drop index可以在alter table內部作為一條語句處理,其格式如下:

drop index index_name on table_name ;

alter table table_name drop index index_name ;

alter table table_name drop primary key ;

其中,在前面的兩條語句中,都刪除了table_name中的索引index_name。而在最後一條語句中,只在刪除primary key索引中使用,因為乙個表只可能有乙個primary key索引,因此不需要指定索引名。如果沒有建立primary key索引,但表具有乙個或多個unique索引,則mysql將刪除第乙個unique索引。

如果從表中刪除某列,則索引會受影響。對於多列組合的索引,如果刪除其中的某列,則該列也會從索引中刪除。如果刪除組成索引的所有列,則整個索引將被刪除。

刪除索引的操作,如下面的**:

mysql> drop index shili on tpsc ;

query ok, 2 rows affected (0.08 sec)

records: 2 duplicates: 0 warnings: 0

該語句刪除了前面建立的名稱為「shili」的索引。

資料庫表的建立**

create table mytable (

id serial primary key,

category_id int not null default 0,

user_id int not null default 0,

adddate int not null default 0

);

為mysql資料庫建立索引

code 如下 create table mytable id serial primary key,category id int not null default 0,user id int not null default 0,adddate int not null default 0 很簡...

為mysql資料庫建立索引

前些時候,一位頗高階的程式設計師居然問我什麼叫做索引,令我感到十分的驚奇,我想這絕不會是滄海一粟,因為有成千上萬的開發者 可能大部分是使用mysql的 都沒有受過有關資料庫的正規培訓,儘管他們都為客戶做過一些開發,但卻對如何為資料庫建立適當的索引所知較少,因此我起了寫一篇相關文章的念頭。最普通的情況...

為mysql資料庫建立索引

前些時候,一位頗高階的程式設計師居然問我什麼叫做索引,令我感到十分的驚奇,我想這絕不會是滄海一粟,因為有成千上萬的開發者 可能大部分是使用mysql的 都沒有受過有關資料庫的正規培訓,儘管他們都為客戶做過一些開發,但卻對如何為資料庫建立適當的索引所知較少,因此我起了寫一篇相關文章的念頭。最普通的情況...