Mysql 更改表結構--增加,修改,刪除
添加列:
alter table tablename add column datatype [primary key/default/not null/...] after 'columnX' //在colunmX列后增加字段
例:在student表中添加一個年級(grade)字段,類型為varchar,不能為null,在age字段后面
alter table student add grade varchar(2) not null after age;
添加后,表結構如下所示:
刪除列:
alter table tablename drop column;
例:將student表中的grade列刪除
alter table student drop grade;
修改后,表結構如下:
修改列--重命名列 / 更改列的數據類型:
alter table 表名 change 原列名 新列名 數據類型 [primary key/default/not null/...];(change 既能重命名列,也可以更改列的數據類型)
alter table 表名 modify 列名 數據類型
更改列名
例:將gender更名為sex
alter table student change gender sex varchar(10);
修改后,表結構如下:
更改列數據類型
例:將grade列數據類型更改為int型
alter table student change gender gender int(2);
修改后,表結構如下:
例:將grade列數據類型更改為varchar型
alter table student modify grade varchar(2);
修改表名:
alter table 表名 rename to 新表名;
例:將student表名更改為students
alter table student rename to students;
修改表后,表結構如下:
添加約束:
mysql常用五類約束類型:
not null:非空約束,指定某列不為空
unique: 唯一約束,指定某列和幾列組合的數據不能重復
primary key:主鍵約束,指定某列的數據不能重復、唯一
foreign key:外鍵,指定該列記錄屬於主表中的一條記錄,參照另一條數據
check:檢查,指定一個表達式,用於檢驗指定數據
注意: MySQL不支持check約束,但可以使用check約束,而沒有任何效果;
alter table 表名 add [constraint 約束名] 約束類型(column1,[column2,column3,...]);
例:給student表添加主鍵name;
alter table student add primary key(name);
刪除約束:
alter table 表名 drop 約束;
例: 刪除student表的主鍵約束
alter table student add primary key;
修改表后,表結構如下:
注:
1. 刪除唯一性約束,語法必須如下:
alter table 表名 drop index 約束名;
若不加index,無法刪除唯一性約束。
例:給students表的name列添加唯一性約束,然后刪除。
alter table students add constraint unique_name UNIQUE(name);
alter table students drop unique_name;(報錯,無法刪除唯一性約束)
alter table students drop index unique_name;(正確)
修改后,表結構如下:
2.刪除主鍵約束:
刪除主鍵約束時,無法使用約束名來刪除主鍵約束。
例:對students表name列增加主鍵約束,然后刪除
alter table students add constraint primary_key_name primary key(name);
刪除主鍵:
alter table students drop primary_key_name;(錯誤,無法刪除)
alter table students drop primary key;(刪除成功)
