在MySQL中, 有四種類型的索引,?
主鍵, 唯一索引, 全文索引和普通索引
主鍵(Primary Key)就是值唯一并且沒有值為NULL的域的索引
NULL
#創(chuàng)建表, 并設(shè)置主鍵
mysql> create table pk_test(
-> f1 int not NULL,
-> primary key(f1));
#已存在的表上創(chuàng)建主鍵, 語法: alter table tablename add primary key(fieldname1 [, fieldname2])
mysql> alter table customer modify id int not null, add primary key(id);
普通索引容許重復(fù)的值
#創(chuàng)建普通索引語法 mysql> create table(fieldname columntype, fieldname2 columntype, index[indexname](fieldname1 [,fieldname2...]));
#創(chuàng)建后添加索引: alter table tablename add index[indexname](fieldname1 [,fieldname2...]);
mysql> alter table sales add index(value);
全文索引
#創(chuàng)建全文索引語法 mysql> create table(fieldname columntype, fieldname2 columntype, fulltext[indexname](fieldname1 [,fieldname2...]));
mysql> insert into ft2 values
-> ('Waiting for the barbarians'),
-> ('In the Heart of the Country'),
-> ('The master of Patersbury'),
-> ('Writing and Being'),
-> ('Heart of the Beast');
-> ('Heart of the Beest'),
-> ('The beginning and the End'),
-> ('Master Master'),
-> ('A barBarian at my door');
Query OK, 4 rows affected (0.00 sec)
#創(chuàng)建表后再添加全文索引:alter table tablename add fulltext[indexname](fieldname1 [,fieldname2...]);
mysql> create table ft(f1 varchar(255), f2 text, f3 blob, f4 int);
mysql> alter table ft add fulltext(f1, f2);
全文索引的用法
文本域查找與大小寫無關(guān)
# match()匹配屬性, against()匹配值
mysql> select * from ft2 where match(f1) against ('master');
唯一索引除了不容許有重復(fù)的記錄外, 與普通索引一樣
#創(chuàng)建普通索引語法 mysql> create table(fieldname columntype, fieldname2 columntype, unique(fieldname1 [,fieldname2...]));
mysql> create table ui_test(f1 int, f2 int, unique(f1));
mysql> insert into ui_test values(1, 2);
#f1域不能包含重復(fù)值
mysql> insert into ui_test values(1, 3);
ERROR 1062 (23000): Duplicate entry '1' for key 'f1'
#創(chuàng)建后添加索引: alter table tablename add unique[indexname](fieldname1 [,fieldname2...]);
#刪除主鍵
alter table tablename drop primary key;
#刪除普通, 唯一, 全文索引, 需要制定索引名
alter table tablename frop index indexname;
#顯示全部索引名
show keys from tablename;
更多建議: