MySQL中索引的创建问题
索引是快速搜索的关键。MySQL索引的建立对于MySQL的高效运行是很重要的。在数据库表中,对字段建立索引可以大大提高查询速度。
MySQL索引类型包括:
(1)普通索引
这是最基本的索引,它没有任何限制。它有以下几种创建方式:
◆创建表的时候直接指定
create table mytable(
id int not null,
username varchar(16) not null,
index indexName (username)
);
◆创建索引
create index indexName on mytable(username);
◆修改表结构
alter table mytable add index indexName (username);
◆删除索引
drop table mytable;
(2)唯一索引
它与前面的普通索引类似,不同的就是:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。它有以下几种创建方式:
◆创建表的时候直接指定
create table mytable(
id int not null,
username varchar(16) not null,
unique indexName (username)
);
◆创建索引
create unique index indexName on mytable(username);
◆修改表结构
alter table mytable add unique indexName (username);
(3)主键索引
它是一种特殊的唯一索引,不允许有空值。一般是在建表的时候同时创建主键索引:
create table mytable(
id int not null,
username varchar(16) not null,
primary key(id)
);
当然也可以用 ALTER 命令。记住:一个表只能有一个主键。
(4)组合索引
为了形象地对比单列索引和组合索引,为表添加多个字段:
create table mytable(
id int not null,
username varchar(16) not null,
city varchar(50) not null,
age int not null
);
将 name, city, age建到一个索引里:
alter table mytable add index name_city_age (username, city, age);
这就是我总结的MySQL中索引的基本创建,代码亲测无误,本人初入博客菜鸟,请各位大神指点。