一: 修改表信息
1.修改表名
-- 修改表名为studen1
alter table student rename to student1;
2.修改表注释
-- 修改表注释
alter table student comment '学生表';
二:修改字段信息
1、(批量)新增字段
-- 增加一个字段,默认为空
alter table student add COLUMN sname VARCHAR(20) DEFAULT NULL;
-- 增加一个字段,默认不能为空
alter table student add COLUMN sname VARCHAR(20) NOT NULL;
----------------------------------
批量添加字段:
方法一:alter table 表名 add (字段1 类型(长度),字段2 类型(长度),字段3 类型(长度));
方法二:事务:
begin; --事务开始
alter table student add sid int(11);
alter table student add sname varchar(20);
alter table student add age varchar(4);
commit; --提交事务
2、删除一个字段
-- 删除一个字段
alter table student DROP COLUMN age;
3、修改字段名字(要重新指定该字段的类型,否则会报错,长度、默认值以及注释等随意)
1、mysql修改字段类型:
--能修改字段类型、类型长度、默认值、注释
--对某字段进行修改(注意:一定要指定新的数据类型,否则会报错,长度、默认值以及注释可以不写)
ALTER TABLE 表名 MODIFY COLUMN 字段名 新数据类型 新类型长度 新默认值 新注释; -- COLUMN可以省略
alter table table1 modify column column1 decimal(10,1) DEFAULT NULL COMMENT '注释'; -- 正常,能修改字段类型、类型长度、默认值、注释
----------------------------------------------------------------------------------
2、mysql修改字段名:
ALTER TABLE 表名 CHANGE 旧字段名 新字段名 新数据类型;
alter table table1 change column1 column1 varchar(100) DEFAULT 1.2 COMMENT '注释'; -- 正常,此时字段名称没有改变,能修改字段类型、类型长度、默认值、注释
alter table table1 change column1 column2 decimal(10,1) DEFAULT NULL COMMENT '注释' -- 正常,能修改字段名、字段类型、类型长度、默认值、注释
alter table table1 change column2 column1 decimal(10,1) DEFAULT NULL COMMENT '注释' -- 正常,能修改字段名、字段类型、类型长度、默认值、注释
----------------------------------------------------------------------------------
alter table table1 change column1 column2; -- 报错
----------------------------------------------------------------------------------
3、批量修改字段名:
alter table 表 change 修改前字段名 修改后字段名称 int(11) not null,
change 修改前字段名 修改后字段名称 int(11) not null,
change 修改前字段名 修改后字段名称 int(11) not null,
change 修改前字段名 修改后字段名称 int(11) not null,
change 修改前字段名 修改后字段名称 int(11) not null;
4、在某个字段后增加字段
-- 在sid这个字段后面添加
alter table studnet add column cid int(11) not null default 0 AFTER sid;
5、调整字段顺序
-- alter table 表名 change 字段名 新字段名 字段类型 默认值 after 字段名(跳到哪个字段之后)
alter table student change sname sname varchar(20) default null after sid ;