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日
祝好!