Mysql中用SQL增加、删除字段,修改字段名、字段类型、设置默认值、注释,调整字段顺序总结

1、增加一个字段

//增加一个字段,默认为空
alter table user add COLUMN new1 VARCHAR(20) DEFAULT NULL; 
//增加一个字段,默认不能为空
alter table user add COLUMN new2 VARCHAR(20) NOT NULL;

2、批量增加字段

方法一:使用事务完成

事务(transaction)是由一系列操作序列构成的程序执行单元,这些操作要么都做,要么都不做,是一个不可分割的工作单位。


bagin;                                           //事务开始
alter table em_day_data add f_day_house7 int(11);
alter table em_day_data add f_day_house8 int(11);
alter table em_day_data add f_day_house9 int(11);
alter table em_day_data add f_day_house10 int(11);
commit;                                             //提交事务,事务结束

方法二:mysql 批量为表添加多个字段

alter table em_day_data add (f_day_house11 int(11),f_day_house12 int(11),f_day_house13 int(11));

3、删除字段

//删除一个字段
alter table user DROP COLUMN new2;

4、修改字段

//修改一个字段的类型
alter table user MODIFY new1 VARCHAR(10);
//修改一个字段的名称,此时一定要重新指定该字段的类型
alter table user CHANGE new1 new4 int;

5、批量修改字段名称

alter table 表 change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null

6、添加注释

// 可以为表添加注释
ALTER TABLE `table_name` COMMENT'注释'; 
// 为字段添加注释,同样适用于修改
ALTER TABLE `table_name` CHANGE `column_name` `column_name` type(longth) UNSIGNED NULL DEFAULT NULL COMMENT '注释'

7、调整字段顺序

alter table 表名 change 字段名 新字段名 字段类型 默认值 after 字段名(跳到哪个字段之后)

alter table appstore_souapp_app_androidmarket;
change getPriceCurrency getPriceCurrency varchar(50)   default null AFTER getPrice;

8、修改默认值

//若本身存在默认值,则先删除
alter table表名alter column字段名drop default;
//然后设置默认值(若本身不存在则可以直接设定)
alter table表名 alter column字段名 set default默认值;

猜你喜欢

转载自blog.csdn.net/qq_16093323/article/details/83892655