MySQL数据库操作3-数据表操作3-修改数据表
时间:2022-03-14 01:50
修改表名:
代码:
alter table 旧表名 rename 新表名;
示例:
alter table peo rename people;
注:完成后可用show tables 查表名是否被修改;
修改表字段的数据类型:
代码:
alter table 表名 modify 字段名 新数据类型;
示例:
alter table people modify name varchar(4);
注:
1.修改之后可以使用 desc 表名 来查看表内数据类型是否被修改,
2.注意可以互相转换的数据类型兼容性,譬如int型的id可以该更char,但是auto_increment属性会失效。原有id值被转换成char型。
修改字段名:
代码:
alter table 表名 change 旧字段 新字段 新数据类型;
示例:
alter table test_t change name xingming char(12);
添加字段:
代码:
alter table 表名 add 新字段名 数据类型;
示例:
alter table test_t add name char(12);
1.
以上字段是默认添加在最后的,且不含约束项,如需约束项秩序要在数据类型后面加上即可。
例如:
alter table test_t add email char(12) not null;
2.
在第一列之前添加字段,需要使用 first选项。
例如:
alter table test_t add addr char(12) not null first;
3.
在制定列之后添加一个字段,需要使用 after 选项。
例如:
alter table test_t add marry char(12) not null after sex;
删除字段:
代码:
alter table 表名 drop 需要删除的字段;
示例:
alter table test_t drop xingming;
修改字段位置:
1.
将字段移到第一位,使用first选项,
代码:
alter table 表名 modify 字段名 数据类型 first;
注:数据类型可以与原字段类型不相同,因此此语句可以同时更改数据类型。
2.
将字段移到指定列位置后面,使用after选项,
代码:
alter table 表名 modify 字段 数据类型 after 字段;
示例:
alter table test_t modify name char(2) first; alter table test_t modify name char(2) after email;
更改表的存储引擎:
代码:
alter table 表名 engine=新引擎名
再次之前最好查看支持的引擎:使用show engines;
同时可以查看默认引擎,使用show variables like ‘storage_engine‘;
删除外键约束:
代码:
alter table 包含外键的表 drop foreign key 外键约束名;
示例:
alter table vice_t drop foreign key s;
删除数据表:
代码:
drop table [if exists] 表名1,.....;
[]为可选参数,如果表名不存在会警告而不是停止执行,建议使用。
此方法用以删除不含关联的表。
注意:
1.如果一个表被外键关联(父表),那么他无法被直接删除,需要先在字表中删除外键关联,或是先删除子表。