本文共 2079 字,大约阅读时间需要 6 分钟。
修改MySQL表结构的常用操作命令
在使用MySQL进行数据库管理时,经常需要对表结构进行修改。以下是一些常用的MySQL操作命令,帮助你快速完成表结构的调整。
一、表名称相关操作
rename
命令快速更改表名称。rename table 旧表名 to 新表名;
例如:
rename table user_table to new_user;
二、字段操作
modify
选项。alter table 表名 modify column 字段名 字段类型(长度);
例如:
alter table user_info modify column age int(11);
change
选项。alter table 表名 change 现有字段名称 修改后字段名称 数据类型;
例如:
alter table user_data change old_column new_column varchar(255);
add
选项。alter table 表名 add 字段名 字段类型(长度);
或者批量添加多个字段:
alter table 表名 add (字段名1 字段类型(长度), 字段名2 字段类型(长度), ...);
例如:
alter table user_info add gender enum('M','F');alter table user_info add (age int(11), status tinyint(1));
drop column
选项。alter table 表名 drop column 字段名;
或者批量删除多个字段:
alter table 表名 drop column 字段名1,drop column 字段名2;
例如:
alter table user_data drop column inactive;alter table user_data drop column created_at, drop column updated_at;
set default
选项。alter table 表名 alter column 字字段 set default 默认值;
例如:
alter table user_info alter column is_admin set default true;
add
时同时指定 default
和 comment
选项。alter table 表名 add 字字段名 字段类型(长度)default null comment '备注';
例如:
alter table user_data add remark text(255) default null comment '备注';
comment
选项。alter table 表名 comment '注释';
例如:
alter table user_table comment '用户信息表';
三、索引操作
add index
选项添加普通索引。alter table 表名 add index 索引名 ( 字字段名 );
例如:
alter table user_info add index idx_age age;
add primary key
选项创建主键索引。alter table 表名 add primary key ( 字字段名 );
例如:
alter table user_data add primary key (id);
add unique
选项创建唯一索引。alter table 表名 add unique ( 字字段名 );
例如:
alter table user_info add unique (email);
add fulltext
选项创建全文索引。alter table 表名 add fulltext( 字字段名 );
例如:
alter table user_search add fulltext(product_name);
add index
中指定多个字段。alter table 表名 add index 索引名 ( 字字段名, 字字段名, 字字段名 );
例如:
alter table user_info add index idx_search (username, email);
以上命令可以帮助你快速完成MySQL表结构的修改和优化工作。
转载地址:http://fddfk.baihongyu.com/