一. 列常用操作 ① 添加新的一列test_column,並將其作為主鍵,FIRST將其放在表中第一行,auto_increement是自動增長 1 可以使用SQL語句“alter table ai3 add id0 int auto_increment primary key first;”來添加 ...
一. 列常用操作
① 添加新的一列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;