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 2018-08-08 10:13  快舔包我很肥  阅读(9328)  评论(0编辑  收藏  举报

导航