MySQL表及索引相关知识

1.表

1.1)建表

create table student(

id int(4) not null,
name char(20) not null,
age tinyint(2) not null default '0',
dept varchar(16) default null);

show create table student\G

1.2)查看建表的结构

desc student;

show columns from student;

1.3)查看已建表的语句

show create table student\G

2.索引

2.1 索引类型

1)主键索引:每个表只能有一个主键列

create table student(
id int(4) not null AUTO_INCREMENT,
name char(20) not null,
age tinyint(2) not null default '0',
dept varchar(16) default NULL,
primary key(id),
KEY index_name(name)
);

也可后来再添加主键:

alter table student change id id int primary key auto_increment;

2)普通索引

alter table student drop index index_name;            #或者用drop index index_name on student;

alter table student add index index_name(name);

create index index_dept on student(dept(8));         #对dept列的前八个字符创建索引(指定对前n个字符创建索引)

show index from student\G                                     #显示某表中有的索引,mysql默认的索引一般都是BTREE索引

3)联合索引

create index index_name_dept on student(name,dept);   #也可限定name的前n个字符和dept的前m个字符

4)唯一索引(非主键索引)

create unique index index_name on student(name);

2.2 索引的创建条件

索引是要占空间的,而且需要维护,因此创建索引要遵循一定条件:

要在表的列上创建索引;

索引会加快查询速度,但是会影响更新速度;

select user,host from mysql.user where host=....索引一定要创建在where后的条件列上,而不是select后的选择数据的列;

尽量选择在唯一值多(比如这个表就男或女两个选项)的大表上的列建立索引。

2018年10月30日

祝好!

原文地址:https://www.cnblogs.com/wangke2017/p/9524430.html