MySQL添加列、删除列,创建主键等常用操作总结

一. 列常用操作

① 添加新的一列test_column,并将其作为主键,FIRST将其放在表中第一行,auto_increement是自动增长

alter table test_table add column test_column int not null auto_increment FIRST add primary key(test_column);
  • 1

 

可以使用SQL语句“alter table ai3 add id0 int  auto_increment primary key first;”来添加主键列。可以使用SQL语句“alter table ai4 modify id int auto_increment primary key;”来修改主键列。



② 删除列

 

alter table test_table drop column test_column;
  • 1

③ 修改某一列的字段长度(例如本来是30字节改为50字节长)

alter table test_table modify column test_column varchar(50);
  • 1

④ 完全修改某一列(假设原本列名是test1_column,类型是int)

alter table test_table change column test1_column test_column varchar(30);
  • 1

⑤ 仅仅想重命名某一列(首先需要了解这一列的类型,假如原本是int且不为空,列名是error_name_column)

alter table test_table change column error_name_column test_column int not null;
  • 1

二. 针对表的多数操作

① 修改指定表的存储引擎,假设原本是MYISAM

alter table test_table engine=innodb;
  • 1

② 删除指定表的主键

alter table test_table drop primary key;
  • 1

这里有个情况需要指出,如果该主键列是自动增长(auto_increment)的,因为mysql要求自动增长列必须是索引,所以删除主键也就删除了主键索引,这是不符合mysql要求的,是无法实现的,会报错,必须先删除自动增长(通过修改列属性),后删除主键

③ 为指定表添加主键

alter table test_table add primary key(test_column);
  • 1

④ 为指定表添加索引(普通索引),test_index是索引名

alter table test_table add index test_index(test_column);
  • 1

⑤ 删除指定表索引

alter table test_table drop index test_index;
  • 1

⑥ 重命名表

alter table test_table rename new_name_table;

 

 



 

 

如果想在一个已经建好的表中添加一列,可以用诸如:

alter table TABLE_NAME add column NEW_COLUMN_NAME varchar(20) not null;

这条语句会向已有的表中加入新的一列,这一列在表的最后一列位置。如果我们希望添加在指定的一列,可以用:

alter table TABLE_NAME add column NEW_COLUMN_NAME varchar(20) not null after COLUMN_NAME;

注意,上面这个命令的意思是说添加新列到某一列后面。如果想添加到第一列的话,可以用:

alter table TABLE_NAME add column NEW_COLUMN_NAME varchar(20) not null first;

posted on   快舔包我很肥  阅读(9353)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示