【场景】:删除表的结构和数据 【分类】:删除记录、truncate、drop、delete
分析思路
难点:
1.如何删除数据并重置自增ID
如何删除数据并重置自增ID
方法一、truncate
情况表中的记录并重置自增id。
- [使用]:
truncate table
- [注意]:truncate只能作用于表;truncate会清空表中的所有行,但表结构及其约束、索引等保持不变;truncate会重置表的自增值;使用truncate后会使表和索引所占用的空间会恢复到初始大小。
方法二、drop
删除表的数据和结构之后重新建表。
- [使用]:
drop table if exists exam_record;create table if not exists exam_record...
- [注意]:drop会删除表的结构及其所依赖的约束、索引等;drop语句将表所占用的空间全释放掉。所以使用之后需要重建表。
不可用delete
delete删除表中的元组并且不会重置表的自增值;delete操作不会减少表或索引所占用的空间;delete并不能删除表的结构,所以不能像drop一样用于删除表的结构之后再重新建表。delete多于用删除部分数据。
扩展
前往查看:MySQL 删除数据
求解代码
方法一:
删除表中数据并重置表的自增ID
truncate table exam_record
方法二:
删除表的数据和结构之后重新建表
drop table if exists exam_record;
create table if not exists exam_record(
id int(11) primary key AUTO_INCREMENT comment '自增ID',
uid int(11) not null comment '用户ID',
exam_id int(11) not null comment '试卷ID',
start_time datetime not null comment '开始时间',
submit_time datetime comment '提交时间',
score tinyint(4) comment '得分'
)character set utf8 collate utf8_general_ci