1.创建表
(1)创建表
create database if not exists test01(
id int(n) auto_increment not null,
name varchar(6) not null,
primary key(`id`)
)engine=InnoDB default charset=utf8
(2)删除表
drop table 表名
(3)复制表结构
create table if not exists 新表名 like 旧表名
(4)查看表结构
desc 表名
(5)复制表
create table if not exists 新表名 as select * from 旧表名
(6)更改表名
alter table 表名 rename [as] 新名字
或者
rename table 旧表名 to 新表名
2.修改表结构
(1)增加一个新字段
alter table 表名 add [column] 列名 int(6) not null
(2)增加一个主键
alter table 表名 add primary key(`id`)
注意: 增加主键并不会自动增加自增,需要手动设置自增
(3)增加唯一索引
alter table 表名 add unique [索引名字] (`name`)
(4)修改字段名称
alter table 表名 change 旧字段名 新字段名 类型(长度)
例如:alter table academy change `name` `newname` varchar(20)
注意: 一定类型写错,类型便会更改
(5)修改字段类型
alter table 表名 modify 字段名 类型(长度)
(6)删除字段
alter table 表名 drop [column] 字段名
注意: 无论字段是否有约束与索引,都可以直接删掉
(7)删除索引名字
alter table 表名 drop index 索引名
注意: 只要是索引,都可以删除,不管是什么索引
3.修改约束条件
(1)常用约束分类
主键约束(prmary key)、外键约束(foreign key)、默认值约束(default)、唯一性约束(unique)、非空约束(not null)、检查约束(check)
(2)增加约束条件
alter table 表名 add constraint 约束名 约束类型(字段名)
唯一性约束:alter table academy add constraint academy_unique Unique(`id`)
注意: 此语法仅适用于主键、外键、唯一性,check约束
默认值、自增、非空约束则使用一下语法
alter table 表名 modify 字段名 类型(长度)约束类型
默认值约束:alter table academy modify `name` varchar(20) default '大数据与软件学院'
自增约束:alter table academy modify `id` int auto_increment
非空约束:alter table academy modify `nama` varchar(20) not null
(3)删除约束
主键约束:alter table 表名 drop primary key
外键约束:alter table 表名 drop foreign key 约束名
唯一性约束:alter table 表名 drop index 索引名
非空约束:alter table 表名 modify 字段名 类型(长度) null
默认值约束:alter table 表名 modify 字段名 类型(长度)default null
4.其他修改选项
(1)修改存储引擎
alter table 表名 Engine=InnoDB
(2)修改字符集
alter table 表名 default charset=utf8
(3)修改当前自增数
alter table 表名 字段名 auto_increment=100
写在最后: alter语句可能在对表进行更改时,需要删除全部数据才能执行成功,例如,把varchar类型转换为Enum
创建数据库的语句:create database if not exists 表名 Character set=utf8 default collate utf8_general_ci