1.修改字段
修改表的结构使用 alter table 语句,具体语法如下:
alter table 数据表名 alter子句 ……
add 列名 | 添加新字段 |
add index 索引名 | 添加索引名称 |
add primary key | 添加主键名称 |
add unique 索引名 | 添加唯一索引 |
alter 列名 | 修改字段名称 |
change 列名 | 修改字段类型 |
modify 列名 | 修改子句定义字段 |
drop 列名 | 删除字段名称 |
drop index 索引名 | 删除索引名称 |
drop primary key | 删除主键名称 |
rename | 更改表名 |
alter table语句允许指定多个动作,其间使用逗号分隔开,每个动作表示一个修改。例如: alter table test1 add grade varchar(20) not null ,modify time datetime(6) ;
通过alter修改表列的前提,必须是将表中数据全部删除。
2.修改约束条件
对数据表的约束条件修改,主要包括添加约束条件和删除约束条件两种。
(1)添加约束条件
alter table 数据表名 add constraint 约束名 约束类型(字段名)
primary key | 主键约束 |
default | 默认值约束 |
unique key | 唯一约束 |
not null | 非空约束 |
foreign key | 外键约束 |
(2)删除约束
删除主键约束:alter table 表名 drop primary key
删除外键约束:alter table 表名 drop foreign key 约束名
删除唯一性约束:alter table 表名 drop index 唯一索引名
3.修改表的其他选项
修改表的存储引擎:alter table 表名 engine=新的存储引擎类型
修改表的字符集: alter table 表名 default charset=新的字符集
修改表的自增类型字段的初始值:alter table 表名 auto_increment==新的初始值
4.修改表名
rename table 数据表名1 to 数据表名2
该语句可以同时对多个数据表进行重命名,其间以逗号分隔开。
5.删除表
drop table 表名
一旦删除数据表过后,表中的数据会全部清除,没有备份则无法恢复。并且,若删除了一个不存在的表将会产生错误,此时可以使用如下语句:
drop table if exists 表名