您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

MySql之ALTER命令用法详细解读_MySQL

2024/8/1 7:31:23发布219次查看
本文详细解读了mysql语法中alter命令的用法,这是一个用法比较多的语法,而且功能还是很强大的。
use learning;(自己要提前建好)create table student(id int not null,name char(10) not null,class int not null,age int);
来看看新建好的表
一、删除,添加或修改表字段删除表字段
如下命令使用了 alter 命令及 drop 子句来删除以上创建表的 age字段:
alter table student drop age;
来看看结果:
如果数据表中只剩余一个字段则无法使用drop来删除字段。
添加表字段mysql 中使用 add 子句来想数据表中添加列,如下实例在表 student 中添加age字段,并定义数据类型:
alter table student add age int not null;
执行以上命令后,i 字段会自动添加到数据表字段的末尾。
show columns from student来看表结构
如果你需要指定新增字段的位置,可以使用mysql提供的关键字 first (设定位第一列), after 字段名(设定位于某个字段之后)。
尝试以下 alter table 语句, 在执行成功后,使用 show columns 查看表结构的变化:
alter table student add sex char(2) first;
first 和 after 关键字只占用于 add 子句,所以如果你想重置数据表字段的位置就需要先使用 drop 删除字段然后使用 add 来添加字段并设置位置。
alter table student drop sex;alter table student add sex char(2) after age;
修改表字段
修改字段类型及名称
如果需要修改字段类型及名称, 你可以在alter命令中使用 modify 或 change 子句 。
例如,把字段 name 的类型从 char(10) 改为 char(100),可以执行以下命令:
alter table student modify age char(100);
使用 change 子句, 语法有很大的不同。 在 change 关键字之后,紧跟着的是你要修改的字段名,然后指定新字段的类型及名称。尝试如下实例:
alter table student change id stu_id bigint primary key;
alter table 对 null 值和默认值的影响
当你修改字段时,你可以指定是否包含只或者是否设置默认值。
以下实例,指定字段sex为 not null 且默认值为男 。
alter table sutdent modify sex char(2) not null default '男';
如果你不设置默认值,mysql会自动设置该字段默认为 null。
你也可以使用 alter 命令及 drop子句来删除字段的默认值,如下实例:
alter table student alter sex drop default; show columns from student;
修改数据表类型,可以使用 alter 命令及 type 子句来完成。尝试以下实例,我们将表 student的类型修改为 myisam :
注意:查看数据表类型可以使用 show create table 语句。
alter table student engine = myisamshow create table student;
二、修改表名如果需要修改数据表的名称,可以在 alter table 语句中使用 rename 子句来实现。
尝试以下实例将数据表 student 重命名为 student_1:
mysql> alter table student rename to student_1;
三、主键和索引修改删除表中主键
alter table student drop primary key;
添加主键
alter table student add constraint pk_student primary key (id,class);
添加索引
alter table student add index index_name (name);
查看索引
show index from student;
添加唯一限制条件索引
alter table student add unique emp_name(age);
删除索引
alter table student drop index index_name;
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product