格式: alter table 表名 action(更改选项);
更改选项:
1. 添加字段:alter table 表名 add 字段名信息
例如:
-- 在user表的最后追加一个num字段 设置为int not null
mysql> alter table user add num int not null;
-- 在user表的email字段后添加一个age字段,设置int not null default 20;
mysql> alter table user add age int not null default 20 after email;
-- 在user表的最前面添加一个aa字段设置为int类型
mysql> alter table user add aa int first;
2. 删除字段:alter table 表名 drop 被删除的字段名
例如:-- 删除user表的aa字段
mysql> alter table user drop aa;
3. 修改字段:alter table 表名 change[modify] 被修改后的字段信息
其中:change可以修改字段名, modify 不修改
例如:
-- 修改user表中age字段信息(类型),(使用modify关键字的目的不修改字段名)
mysql> alter table user modify age tinyint unsigned not null default 20;
-- 修改user表的num字段改为mm字段并添加了默认值(使用change可以改字段名)
mysql> alter table user change num mm int not null default 10;
4. 添加和删除索引
-- 为user表中的name字段添加唯一性索引,索引名为uni_name;
mysql> alter table user add unique uni_name(name);
-- 为user表中的email字段添加普通索引,索引名为index_eamil
mysql> alter table user add index index_email(email);
-- 将user表中index_email的索引删除
mysql> alter table user drop index index_email;
5. 更改表名称:
ALTER TABLE 旧表名 RENAME AS 新表名
6. 更改AUTO_INCREMENT初始值:
ALTER TABLE 表名称 AUTO_INCREMENT=1
7. 更改表类型:
ALTER TABLE 表名称 ENGINE="InnoDB"