基本介紹:修改表,就是指,當我們的表創建好了,根據業務邏輯的需要, 我們要對表進行修改(比如 修改表名, 增加字段,刪除字段,修改字段長度,修改字段類型), 這時我們就要使用修改表技術
查看表結構:desc 表名;
案例演示:
--創建表 create table staff( id int not null default 1 comment "序列號", name varchar(5) not null default '保密' comment '姓名', sex enum('男','女','保密') not null default '保密' comment '性別', birthday date comment '生日', entry_date date comment '入職日期', station varchar(20) not null default '保密' comment '職位', salary decimal(10,2) unsigned not null default 0 comment '薪資', resume text comment '文章' )charset=utf8 engine=myisam; --插入數據 insert into `staff` value(6,'老王',1,'1976-9-8','2014-5-18','保潔',3900.00,' '); insert into `staff` value(10,'小明',1,'1992-7-16','2016-5-18','保潔',13000.00,' '); --查看表 select * from `staff`; --查看表結構 desc `staff`; --在員工表上增加一個戶籍地址的列 alter table `staff` add `address` varchar(20) not null default '' comment '戶籍地址'; --修改崗位(station)列其長度為60默認值為空 alter table `staff` modify `station` varchar(60) not null default '' comment '職位'; --刪除文章(resume)列 alter table `staff` drop `resume`; --修改表名為worker rename table `staff` to `worker`; --修改表的字符集為utf8 alter table `worker` character set utf8; --修改字段名name為staff_name長度改為64默認值改為空; alter table `worker` change name staff_name varchar(64) not null default '' comment '姓名';
案例說明:
(1) 添加列可以在后面給列設定位置(比如說:alter table `staff` add `address` varchar(20) not null default '' comment '戶籍地址' after `sex`;就是在sex后面插入列)
(2) 修改字段名的同時也可以修改字段信息
注意事項:
(1) 如果我們刪除了某個字段,那么這個表的該字段內容就刪除,所以要小心
(2) 如果我們把一個字段的長度減小 varchar(64) ==> varchar(32) , 如果你當前這個字段沒有任何數據,是可以ok,但是如果已經有數據則看實際情況,就是如果有數據超過 32 了,則會提示錯誤.
(3) 對字段類型的修改, 比如 varchar ==> int 那么要看你的varchar 的內容是否可以轉成int, 'hello'=>int 就不能成功。