您的位置:首页 > 数据库 > MySQL

MySQL 索引介绍 属性介绍 注意事项

2016-07-05 16:41 405 查看
【查看 一张表上的索引】
show index from 表名;
show index from 表名 \G;        //可以横着显示

【一、】添加索引
第一种方法:

【主键索引】:
create table tab2(
id int,
primary key(id)
);

【唯一索引】(索引名可选,不写索引名,默认为这一列的列名):
create table tab3(
name char(10),
unique [索引名] (name)
);

【常规索引,也叫普通索引】(索引名可选,不写索引名,默认为这一列的列名):
create table tab4(
name char(10),
index(key) [索引名] (name)
);

【全文索引】(MyISAM 表类型使用, 只有在varchar char text文本字符串上使用)(索引名可选,不写索引名,默认为这一列的列名):
create table tab5(
name char(10),
fulltext [索引名] (name)
);

【二、】添加索引
第二种方法:

【主键索引】:
alter table 表名 add primary key;

【唯一索引】(索引名可选,不写索引名,默认为这一列的列名):
alter table 表名 add unique [索引名] (字段名);

【常规索引,也叫普通索引】(索引名可选,不写索引名,默认为这一列的列名):
alter table 表名 add index [索引名] (字段名);
alter table 表名 add key [索引名] (字段名);

【全文索引】(索引名可选,不写索引名,默认为这一列的列名):
alter table 表名 add fulltext [索引名] (字段名);

【全文索引应用】:
select 列名, match (索引) against (‘ 索引词’) from 表名;
select * from
表名 where match (索引) against (‘ 索引词’);
【举例】:
create table books(
id int,
bookname varchar(10),
price double,
detail text not null,
fulltext(detail,bookname),
index ind(price),
primary key(id)
);
select * from books where bookname like '%php%';
select bookname,price from books where match(detail) against('php');
select match(detail) against('php') from books;

【三、】删除索引

【删除主键索引】(注意:如果主键有自增长,得先删除自增长):
alter table 表名 change id id int; //删除自增长
alter table 表名 drop primary key;

【第一种方法(删除唯一、常规(普通)、全文索引)】:
drop index 索引名 on 表名;

【第二种方法(删除唯一、常规(普通)、全文索引)】:
alter table 表名 drop index 索引名;

【四、】添加属性:

【无符号:unsigned】:正数,可以让空间增加一倍 只能用在数值型字段

【前导0:zerofill】:只能用在数值型字段

【不为空:NOT NULL】

【缺省值:default】

【自动增长:AUTO_INCREMENT】
【举例】:
create table tab8(
id int unsigned zerofill not null AUTO_INCREMENT primary key
);

create table tab9(
name varchar(10) not null default ''
); 

【五、】注意事项:

【添加属性自动增长,必须先设置为主键】
alter table 表名 add primary key;
alter table 表名 change id id int unsigned zerofill not null AUTO_INCREMENT;

【删除主键索引】(注意:如果主键有自增长,得先删除自增长):
alter table 表名 change id id int; //删除自增长
alter table 表名 drop primary key;

【常规索引,也叫普通索引】单独使用:
create index 索引名 on 表名 (字段名);

【只有主键索引,唯一索引,可以直接在后面添加。】(注意:直接添加唯一索引时,其后不能加索引名。另外常规索引(index or key),全文索引(fulltext)不能直接在其后添加!): 
create table tab1(
id int primary key,
name char(10) unique
);

希望可以帮到你们!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql 索引 属性