mysql的表操作
大约 2 分钟
表操作
查看表
show tables;
创建表
create table user(
id int unsigned primary key auto_increment,
name varchar(50) unique not null,
age tinyint not null,
sex enum("male", "female") not null
)engine=INNODB default charset=utf8;
查看表结构
desc user;
查看建表sql
show create table user\G

删除表
drop table user;
实践中一些接口如果老是报错,先用命令行执行api调用的SQL语句,看一下执行时间是否超时,比如sql执行时间为10s,而api设置的相应等待时间为5s,因此需要优化查询
表操作小结
(1)增create:
create table 表名
(
字段名称 字段类型 字段约束 [注释],
字段名称 字段类型 字段约束 [注释],
…
);//创建一个表;
添加注释
COMMENT
字符集:
latin1
特点为:不能存储中文;若想存储中文使用utf8
(2)删drop:
drop table 表名;删除一个表
(3)改alter:
alter table 表名 modify 字段名称 字段新类型; //修改字段类型方式1
alter table 表名 change 字段名称 字段名称 新字段类型; //修改字段类型方式2
alter table 表名 change 旧字段名 新字段名 新字段类型; //修改字段名
alter table 表名 add 新字段 类型 约束; //表中新添加一个字段
alter table 表名 add 新字段 类型 约束 after 某字段名; //添加一个字段到任意位置之后(除了第一个位置无法处理)
alter table 表名 add 新字段 类型 约束 first; //添加一个字段到首位置
alter table 表名 drop 字段名; //删除字段
alter table 表名 rename 新表名; //修改表名
alter table student modify age int(4); #age数据类型为INT(3)改为INT(4)
alter table student change age age int(4);#新旧都是age,因此只改变数据类型
alter table student change age student_age smallint;#age字段名改为student_age,并同时将其类型改为SMALLINT
alter table student add email varchar(100);#添加一个新的email字段,数据类型为VARCHAR(100);置末
alter table student add birthdate date after email;#添加一个birthdate字段,数据类型为DATE,放在email字段之后
alter table student add student_id int primary key auto_increment first; #首位置添加一个student_id字段,数据类型为INT,并设置为主键(约束):
alter table student drop email;#删除email字段
alter table student rename xuesheng; #将students表重命名为xuesheng
(4)查show:
show tables;查看当前库下的表;
show create table 表名;查看表的创建信息;
desc 表名;查看表字段信息;