MySQL数据库(九):修改表结构

前言:
1.修改表结构的时候受表中已存储数据的限制
2.查看表结构
desc 表名;
1.修改表结构
格式:
alter table 表名 修改动作;
2.修改动作
<add,modify,chang,drop>
1.1 add
添加新字段 (新添加的字段默认追加在已有字段的下方)
格式:
add 字段名(宽度) 约束条件,add 字段名(宽度) 约束条件;
例子:
添加字段
alter table t22 add mail varchar(50) not null default "nsd1503@tarena.com.cn"; alter table t22 add sex enum("boy","girl"),add birthday date; alter table t22 add stu_id char(4) not null first;
在...之后添加一个新字段(after sex:在sex字段之后添加新字段 )
alter table t22 add loves set("game","film","book") not null default "film,book" after sex;
1.2 drop
删除已有字段
格式:
#删除一个字段 drop 字段名; #删除多个字段 drop 字段名,drop 字段名,drop 字段名;
例子:
alter table t22 drop age,drop loves;
1.3 modify
修改已有字段类型
格式:
#修改一个 modify 字段名 新类型(宽度) 约束条件; #修改多个 modify 字段名 新类型(宽度) 约束条件,modify 字段名 新类型(宽度) 约束条件;
例子:
alter table t25 modify name char(5) not null;
1.4 change
修改字段名
格式:
change 源字段名 新字段名 类型(宽度) 约束条件;
例子:
alter table t25 change name newname char(5) not null; alter table t25 change age newage int(2) not null default 300;
2.修改表名
格式:
alter table 源表名 rename [to] 新表名;
例子:
将t20表明修改为newt20
alter table t20 rename newt20;
3.复制表
*注:源表表结构中key列的值不会被复制给新表
格式:
create table 新表名 SQL查询;
例子:
复制newt20表的所有字段到t200表
create table t200 select * from newt20;
值复制newt20表中的name,loves字段到t201表
create table t201 select name,loves from newt20;
4.只复制源表的表结构
格式:
create table 新表名 select * from 源表名 where 条件;
例子:
create table t206 select * from t202 where user is null;