【DB】更改表结构

3 篇文章 0 订阅

(3)小节(2)小节 中都对mysql创建表有个清晰的认识,那么现在就学习如何更改表结构。

一、快速入门

通过一个例子进行深入理解,这里a1表结构如下:

下面的例子对a1的表结构进行更改

1、添加字段

alter table a1 add column s1 int not null default 0 after sex;                       #添加一个字段
alter table a1 add column s2 char(10) null after s1,add column s3 int null after s2; #添加多个字段
alter table a1 add s4 int null,add s5 int null;                                      #添加多个字段方式2
alter table a1 add s6 int null after s4;                                             #同上 设置 

结果如下:

2、删除字段

alter table a1 drop column s6;                 #删除单个    
alter table a1 drop column s4,drop column s5;  #删除多个
alter table a1 drop s3; 

3、调整字段顺序

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

alter table a1 change sex sex int(2) not null after s2;

4、修改字段

alter table 表名
change 字段名 新字段名 字段类型 默认值
或者使用 modify

#修改字段(重命名、修改类型)
alter table a1 change type types int(10) not null default 0;
#modify
alter table a1 modify types char(2) not null default '0';

5、删除主键

alter table a3 drop primary key;

6、添加主键

alter table a3 add id int(11) not null primary key;
#如果设置表中存在的字段为主键
ALTER TABLE person ADD PRIMARY KEY (id);

7、添加唯一索引

alter table a3 add unique title_unique_index (title);
设置字段名title唯一的索引,索引名:title_unique_index

8、添加普通索引

alter table a1 add index s2_index(s2)

9、删除索引

alter table a1 drop index s2_index;

10、把表默认的字符集和所有字符列(CHAR, VARCHAR, TEXT)改为新的字符集

alter table a1 convert to character set utf8

11、修改表某一列的编码

alter table a1 change s1 s1 varchar(255) character set utf8;

12、仅仅改变一个表的默认字符集

alter table a1 default character set utf8;

13、修改表名

rename table a3 to aa;

14、移动表到其他数据库

rename table demo.aa to test.a3;

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值