删除表中数据
1. delete关键字
语法:delete from 表名称 where 删除约束条件
# 删除student表中name字段为张三的那条记录 delete from `student` where name = '张三'; # 删除student表中id字段为1001的那条记录 delete from `student` where id = '1001'; # 删除student表中age字段小于20的所有记录 delete from `student` where age < 20; # 删除student表中所有记录 delete from `student`; -- 不加约束条件,默认删除表中所有记录
2. truncate关键字
语法:truncate [table] 表名
# 删除student表中所有数据 truncate table `student`; -- 方式一 delete from `student`; -- 方式二
注:方式一和方式二实现的效果一样,方式一效率更高。
两种方式实现的效果都是清空表中的所有记录,并没有删除表结构。
3. drop关键字
语法:drop table [if exists] 表名1 [, 表名2, 表名3…]
# 删除student表 drop table `student`;
这种方式会直接删除表结构,即数据库中不再存在
4. 总结
delete,drop,truncate 都有删除表的作用,区别在于:
- 1、delete 和 truncate 仅仅删除表数据,drop 连表数据和表结构一起删除,打个比方,delete 是单杀,truncate 是团灭,drop 是把电脑摔了。
- 2、delete 是 DML 语句,操作完以后如果没有不想提交事务还可以回滚,truncate 和 drop 是 DDL 语句,操作完马上生效,不能回滚,打个比方,delete 是发微信说分手,后悔还可以撤回,truncate 和 drop 是直接扇耳光说滚,不能反悔。
- 3、执行的速度上,drop>truncate>delete,打个比方,drop 是神舟火箭,truncate 是和谐号动车,delete 是自行车。