update命令主要對錶資料進行修改;
alter命令主要是對錶結構進行修改,主要包括新增、修改、刪除。
1、新增
a、新增字段(列)
alter table 【表名】 add 【欄位名】 【字段屬性】;
例:alter table test add num int(10) not null auto_increament default 65 primary key;
後面的屬性可根據需要選擇新增。
b、新增約束
alter table 【表名】add 【約束關係】
例1:新增主鍵約束
alter table test add primary key(id);
例2:新增外來鍵約束
alter table test add foreign key(id) references test2(id);
外來鍵約束名稱自動生成
alter table test add constraint fk_test_test2 foreign key(id) references test2(id);
指定外來鍵約束名稱
2、修改
a、修改表名
alter table 【表名】 rename 【新錶名】
例:alter table test rename test1;
b、修改欄位名
alter table 【表名】 change 【欄位名】 【新欄位名】 integer
例:alter table test change name name1 integer;
c、修改字段屬性
alter table 【表名】 change 【欄位名】 【欄位名】【字段屬性】
注:只修改字段屬性時,兩個欄位名相同
或 alter table 【表名】 modify 【欄位名】 【字段屬性】
例:alter table test change name name varchar(30);
或alter table test modify name varchar(30);
3、刪除
a、刪除字段
alter table 【表名】drop column 【列名】
例:alter table test drop column ***;
b、刪除約束
alter table 【表名】 drop 【約束】
例1:
alter table test drop primary key;
刪除主鍵約束
例2:
alter table test drop foreign key fk_id;
刪除外來鍵約束,fk_id為外來鍵約束名稱
補充:
1、可通過使用show create tabel table_name檢視建表語句來檢視資料型別、約束關係及約束名稱;desc檢視表結構
2、加快alter table的速度,可參考:
Mysql中alter的用法
1 刪除列 alter table 表名字 drop 列名稱 2 增加列 alter table 表名字 add 列名稱 int not null comment 注釋說明 3 修改列的型別資訊 alter table 表名字 change 列名稱 新列名稱 這裡可以用和原來列同名即可 bigint...
mysql的alter用法總結
當表被建立後,在使用過程中可能會有一些新的需求,這時候可能需要修改表的結構。如果表中已經填充了資料,重新建表會造成現有資料的丟失,為此可以用alter table對錶結構進行修改 向表中新增列的前提是所新增的列允許使用null值或者對該列使用default約數指定了預設的值。alter table ...
mysql的alter用法總結
注意 一般情況下,不推薦在建表後對錶進行大幅度修改,大幅度修改極有可能使表資料丟失。因此需要修改之前一定要對錶做好資料備份 刪除列 alter table 表名 drop column 列名 增加列 alter table 表名 add column 列名 屬性 約束 修改列的型別資訊 alter ...