MySQL添加列、删除列,建立主键等经常使用操做总结

一. 列经常使用操做

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

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;”来修改主键列。sql



② 删除列索引

 

alter table test_table drop column test_column;
  • 1

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

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

④ 彻底修改某一列(假设本来列名是test1_column,类型是int)innodb

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

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

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

二. 针对表的多数操做

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

alter table test_table engine=innodb;
  • 1

② 删除指定表的主键test

alter table test_table drop primary key;
  • 1

这里有个状况须要指出,若是该主键列是自动增加(auto_increment)的,由于mysql要求自动增加列必须是索引,因此删除主键也就删除了主键索引,这是不符合mysql要求的,是没法实现的,会报错,必须先删除自动增加(经过修改列属性),后删除主键im

③ 为指定表添加主键error

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;

相关文章
相关标签/搜索