MySQL培訓教程:alter怎么修改MySQL數據庫表
最新學訊:近期OCP認證正在報名中,因考試人員較多請盡快報名獲取最近考試時間,報名費用請聯系在線老師,甲骨文官方認證,報名從速!
我要咨詢我們在創建表的過程中難免會考慮不周,因此后期會修改表
修改表需要用到alter table語句
修改表名
mysql> alter table student rename person;
Query OK, 0 rows affected (0.03 sec)
這里的student是原名,person是修改過后的名字
用rename來重命名,也可以使用rename to
還有一種方法是rename table old_name to new_name
修改字段的數據類型
mysql> alter table person modify name varchar(20);
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
此處modify后面的name為字段名,我們將原來的varchar(25)改為varchar(20)
修改字段名
mysql> alter table person change stu_name name varchar(25);
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
這里stu_name是原名,name是新名
需要注意的是不管改不改數據類型,后面的數據類型都要寫
如果不修改數據類型只需寫成原來的數據類型即可
tips:我們同樣可以使用change來達到modify的效果,只需在其后寫一樣的字段名
增加無完整性約束條件的字段
mysql> alter table person add sex boolean;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
此處的sex后面只跟了數據類型,而沒有完整性約束條件
增加有完整性約束條件的字段
mysql> alter table person add age int not null;
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0
此處增加了一條age字段,接著在后面加上了not null完整性約束條件
增加額外的完整性約束條件
mysql> ALTER TABLE person ADD PRIMARY KEY(id);
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
這里同樣也用于多字段設置
在表頭添加字段
mysql> alter table person add num int primary key first;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
默認情況下添加字段都是添加到表尾,在添加語句后面加上first就能添加到表頭
在指定位置添加字段
mysql> alter table person add birth date after name;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
這里添加一條新字段放在name字段后面
tps:表中字段的排序對表不會有什么影響,不過更合理的排序能便于理解表
刪除字段
mysql> alter table person drop sex;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
和前面刪除表或數據庫一樣,這里也需要用drop
不同的是,刪除字段還要用alter table跟著表名
修改字段到第一個位置
mysql> alter table person modify id int first;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
first在前面已經講過,此處要注意的是字段后面要寫數據類型
修改字段到指定位置
mysql> alter table person modify name varchar(25) after id;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
我們把name字段放到了id后面,此處的varchar(25)要寫全,varchar不行
建議操作以上步驟之前都先desc table
修改表的存儲引擎
mysql> alter table user rename person;
Query OK, 0 rows affected (0.05 sec)
這里先不具體講各個存儲引擎的特點,內容比較多
修改完之后別忘了使用show create table語句查看,第三節有寫用法
tips:如果表中已存在很多數據,不要輕易修改存儲引擎
增加表的外鍵
mysql> alter table score add constraint fk foreign key(stu_id) references student(id);
Query OK, 10 rows affected (0.18 sec)
Records: 10 Duplicates: 0 Warnings: 0
這里只需使用add增加即可,后面的語法參見第四節中的外鍵設置
刪除主鍵
mysql> ALTER TABLE person DROP PRIMARY KEY;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
由于主鍵沒有別名,所以使用drop會刪除所有主鍵
刪除表的外鍵約束
mysql> alter table student3 drop foreign key fk;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
由于基本的表結構描述無法顯示外鍵,所以在進行此操作前最好使用show create table查看表
這里的fk就是剛剛設置的外鍵
需要注意的是:如果想要刪除有關聯的表,那么必先刪除外鍵
刪除外鍵后,原先的key變成普通鍵
至于刪除表的操作,在第三節有寫,設置外鍵在第四節也有寫
如果創建表的時候沒有設置外鍵,可使用上面的方法