1. alter 命令:

  • 用于添加 / 修改 / 删除 表字段

    1. 1 添加表字段 (add)

    1. // 添加表字段 (i) 为字段名 int为字段数据类型
    2. mysql> alter table test2 add i int;
    3. mysql> alter table test2 add name varchar(20);
    4. mysql> alter table test2 add age int;

    image.png

    1.2 删除表字段 (drop)

    1. alter table test2 drop age;
    2. alter table test2 drop i;

    image.png
    如果需要指定新增字段的位置:可以使用关键字 First / 或者 after R , 在 字段 R 后

    1. alter table test2 add i int after id;

    image.png
    如果不指定,则默认从最后开始

    1. alter table test2 add c varchar(20);

    image.png

    2. 修改字段

  • 使用 modify 或者 change

    1. // 使用 modify 只能修改对应字段的数据类型
    2. alter table test2 modify c int;

    image.png

  • 使用 change 可修改 字段名以及字段的数据类型

    1. alter table test2 change c(原字段名) age(新字段名与数据类型) int;

    image.png

    3. 为字段添加默认值 / 指定是否为 Null

  • 这里存在一个问题,就是我们为前面的数据添加 字段的时候,并没有为字段添加值,所以存在问题就是,加入我们要设计 not null ,表里面的 字段都为 null ,这样数据和约束存在冲突,我们需要在其中加入数据

image.png
看到我们需要修改的 i 列 存在 null 值,所以无法设置为 not null 约束

  1. // 先将 i 列 的值全部设置为非空
  2. update test2 set i = 12;

image.png

  1. // 然后将 i 设置为 not null 约束, 并且设置默认值
  2. alter table test2 i bigint not null default 20;

image.png

4. 修改默认字段的默认值

1.1修改

  1. alter table test2 alter i default 100;

image.png

1.2 删除默认值

  1. alter table test2 alter i drop default;

image.png

5. 查看数据库状态:

  1. show table status \G;

image.png

6. 修改表名

  1. // 更改表名
  2. alter table test2 rename to test;

image.png