修改表的各种操作

官网:https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

这里挑几个常用的演示一下:

原表格sql语句:

create table if not exists test1
(
    id     int auto_increment primary key comment '主键id',
    `name` varchar(10) not null,
    sex    bit(1)      not null,
    address varchar(50) not null ,
    phone char(11) not null ,
    createTime timestamp default CURRENT_TIMESTAMP,
    updateTime timestamp default current_timestamp on update current_timestamp
)engine = Innodb CHARACTER SET utf8mb4;

insert into test1(id,name,sex,address,phone) values (null,'情韵',1,'河南省郑州市','13243299121');

给当前表添加一个字段

语法:

ALTER TABLE tbl_name
ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name]

示例:

alter table test1
add column deleted bit(1) default 0;

效果展示:

image-20230203195659072

注意:

如果添加某列没加默认值的话,默认值为null,即使后面修改为有默认值,修改过后原添加的数据不会发生更改,再添加数据时默认值才会生效。

修改当前表的某个字段名称

语法:

ALTER TABLE tbl_name
RENAME COLUMN old_col_name TO new_col_name

示例:

alter table test1
rename column deleted to iddel;

效果展示:

image-20230203200240494

删除当前表中某个字段

语法:

ALTER TABLE tbl_name
DROP [COLUMN] col_name

示例:

alter table test1
drop column iddel;

效果展示:

image-20230203200532674

修改表中字段的位置

语法:

ALTER TABLE tbl_name
MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name]

示例:

# 把updateTime放在最前面
alter table test1
modify column updateTime timestamp default current_timestamp first ;

效果展示:

image-20230203200900310

注意:

这里不可以不把默认值加上,会把字段的默认值丢掉。反之会加上。

删除/重置某个字段的默认值

语法:

ALTER TABLE tbl_name
ALTER [COLUMN] col_name {
        SET DEFAULT {literal | (expr)}
      | SET {VISIBLE | INVISIBLE}
      | DROP DEFAULT
    }

示例:

# 把createTime的默认值移除
alter table test1
alter column createTime drop default;

效果展示:

image-20230203201548021

修改表的名称

语法:

ALTER TABLE tbl_name
 RENAME [TO | AS] new_tbl_name

示例代码:

alter table test1
rename user;

效果展示:

image-20230203201855848

注意:

名字修改后,原表的名字就失效了。

后面还有一些添加/删除约束什么的 ,依照官网可以写出来就行。