一、扩展部分(修改表结构)
1.1 定义
修改表结构是对已经创建好的表进行结构上的修改,在mysql中,主要采用alter table进行修改
二、案例
CREATE table student (
`id` int PRIMARY key auto_increment,
`name` VARCHAR(20) not null
);
SELECT * from student;
INSERT INTO student values (null,'张三');
INSERT INTO student values (null,'李四');
INSERT INTO student values (null,'王五');
三、SQL
3.1 修改表名
语法:
alter table 旧表名 rename [TO] 新表名;
例如:
alter table student rename people;
ALTER table people rename student;
3.2 修改数据类型
语法:
alter table 表名 modify 列名数据类型 约束条件;
例如:
alter table student modify name char(3) not null;
alter table student modify name varchar(20) ;
tips:
当我们修改数据类型的时候,如果表里有数据,那么必须里面的数据符合你要修改的数据类型
3.3 修改列名
语法:
alter table 表名 change 旧列名 新列名 数据类型;
例如:
alter table student change name s_name varchar(20) not null;
3.4 删除列
语法:
alter table 表名 drop 列名;
例如:
alter table student drop s_name;
tips:
删除列的话,那么列里的数据会跟着一起删除,无法还原。
3.5 添加列
语法:
alter table 表名 add 新列名 数据类型 约束条件 [first | after 已存在的列名];
例如:
alter table student add name varchar(20) not null DEFAULT '未命名';
alter table student add birthday date after id;
tips:
after添加的话,带表的是添加到哪个位置之后
如果已经有数据,添加列的值会是默认值,没有设置默认值会是null
3.6 修改列的排列位置
语法:
alter table 表名 modify 列名1 数据类型 约束条件 first | after 列名2;
例如:
alter table student modify birthday date after name;

7726

被折叠的 条评论
为什么被折叠?



