mysql alter的常用用法

增加字段,并加注释:

ALTER TABLE table_name ADD field_name field_type [not null|null|default value][comment '注释'];

如:
增加列时允许为 null

alter table test add price float(6,4) comment '价格';
#或者
alter table test add price float(6,4) null;

增加列时不允许为 null

alter table test add price float(6,2) not null;

增加列时设置默认值(并允许为空):  

alter table ok add price float(6,2) default 100.50;
#或者
alter table ok add price float(6,2) null default 100.50;

增加列时设置默认值并不允许为空    

alter table ok add fuck char(200) not null default 100;

删除字段 

ALTER TABLE table_name DROP field_name;
#如:
alter table ok drop price;

修改原字段名称及类型:  

ALTER TABLE table_name CHANGE old_field_name new_field_name field_type;
#如:
alter table ok change price max char(200);

 修改为自增

alter table tb_name modify field_name int auto_increment primary key
#如
alter table ok modify id int auto_increment primary key;

 修改字段默认值: 

alter table tablename alter column_name drop default; #(若本身存在默认值,则先删除)
alter table tablename alter column_name set default 'newValue';#(若本身不存在则可以直接设定)
#或者用
alter table tablename change field_name field_name default 'newValue'

增加主键  

alter table tabelname add new_field_id int(11) unsigned not null auto_increment ,add primary key (new_field_id);

 重命名表 

alter table old_table_name rename new_table_name;

 加索引

alter table tablename add index 索引名 (字段名1[,字段名2 …]);
#如:
alter table table1 add index t_index_dx (name,sex);

 加主关键字的索引 

alter table tablename add primary key(字段名);
如
alter table t add primary key(id);

 删除某个索引 

alter table tablename drop index 索引名;
如:
alter table tablename drop index index_dx_1;

  加唯一限制条件的索引

alter table tablename add unique 索引名(要添加的字段);
如:
alter table tablename add unique index_unix(max);

  

原文地址:https://www.cnblogs.com/lin3615/p/4517180.html