四、修改表结构

修改表结构

alter table 库名.表名 执行动作;

执行动作:
	添加新字段		add
	修改字段类型		modify
	删除字段		 drop
	修改表名		 change
mysql> create table tb1(
    name char(10), 
    sex enum('boy','girl'), 
    likes set('money', 'eat', 'game', 'std'), 
    address varchar(50)
);

mysql> desc tb1;
......

添加字段

  • 添加新字段

    字段默认添加在所有字段的后面: 
      - alter table 库名.表名 add 字段名 类型 [约束条件];
    设置添加字段在指定字段的后面: 
      - alter table 库名.表名 add 字段名 类型 [约束条件] after 字段名;
    设置添加字段在所有字段的前面: 
      - alter table 库名.表名 add 字段名 类型 [约束条件] first;
    
    mysql> alter table tb1 add phone int(11);
    mysql> alter table tb1 add id int(5) not null after likes;
    mysql> alter table tb1 add uuid int(5) first;
    
    mysql> desc tb1;
    ......
    

修改字段类型

  • 修改字段类型

    修改的字段类型不能与已存的数据冲突(没有数据的话随意)
      - alter table 库名.表名 modify 字段名 类型(宽度) [约束条件];
    设置修改字段在指定字段的后面: 
      - alter table 库名.表名 modify 字段名 类型(宽度) [约束条件] after 字段名;
    设置修改字段在所有字段的前面: 
      - alter table 库名.表名 modify 字段名 类型(宽度) [约束条件] first;
    
    mysql> alter table tb1 modify id int(10) not null first;		# 单纯移动位置时需要指定原有类型参数约束条件
    
  • 修改字段名

    当跟新类型和约束条件是,也可以修改字段类型
    alter table 库名.表名 change 原字段名 新字段名 类型(宽度) 约束条件;
    
    mysql> alter table tb1 change id pid int(10) not null;
    

删除字段

  • 删除字段

    - alter table 库名.表名 drop 字段名;
    
    mysql> alter table tb1 drop phone;
    

修改表名

  • 修改表名

    - alter table 库名.表名 rename 新表名;
    
    mysql> alter table tb1 rename newtb1;
    
posted @ 2021-11-16 10:41  CatdeXin  阅读(315)  评论(0)    收藏  举报