如果你想要修改表的信息,你会发现alter很强大。
我们可以看到这样一张表。
CREATE TABLE `score` (
`student_id` int(10) unsigned NOT NULL,
`event_id` int(10) unsigned NOT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`event_id`,`student_id`),
KEY `student_id` (`student_id`),
CONSTRAINT `score_ibfk_1` FOREIGN KEY (`event_id`) REFERENCES `grade_event` (`event_id`),
CONSTRAINT `score_ibfk_2` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
复制代码
从上往下看表的创建语句,alter可以修改表名、列的属性(列名、数据类型、字符集)、索引的属性(索引名)、表的存储引擎、字符集。
修改表名
举例:alter table score rename to new_score;
修改列的属性
举例:alter table new_score modify score varchar(3) default null;
增加列
alter table new_score add column level varchar(1);
删除列
alter table new_score drop column level;
修改列的字符集
alter table new_score modify score varchar(3) character set utf8;
修改列名
alter table new_score change score score_another varchar(3);
注意,此处用的是change,而不是modify。change能做到,而modify做不到,在修改列数据类型的同时,修改列名。
修改表的引擎
alter table new_score engine = MyISAM;
注意此处修改失败的原因是,表内包含外键。只有InnoDB引擎支持外键。