在MySQL中删除数据有两种方式:
-
truncate(截短)属于粗暴型的清空 -
delete属于精细化的删除
删除操作
如果你需要清空表里的所有数据,下面两种均可:
delete from tablename;
truncate table tablename;
而如果你只是删除一部分数据,就只能使用delete:
delete from tablename where case1 and case2;
区别
在精细化的删除部分数据时,只能使用delete。
而清空所有表数据时,两者均可,此时这两种方式有一定的区别:
返回值
truncate返回值为0,而delete会返回被删除的记录数
mysql> truncate serviceHost;
Query OK, 0 rows affected (0.04 sec)
mysql> delete from serviceHost where creator='test';
Query OK, 4 rows affected (0.01 sec)
自增字段
如果表中有自增字段,truncate会重置为1,而delete会保持自增的最大值。
执行效率
truncate不扫描表,相当于重新创建了表,只保留了表的结构,然后删除掉原有表,效率非常高。delete会扫描全表,根据where语句做判断,因此效率低。
操作日志
truncate不写服务器日志,无法恢复。delete会写服务器日志。
触发器
truncate不激活触发器,delete会激活触发器。
参考资料
- MySQL 清空表(truncate)与删除表中数据(delete) 详解:https://blog.csdn.net/chenshu...
- MySQL中删除数据的两种方法:https://blog.csdn.net/apache6...
- 清空某个mysql表中所有内容:https://blog.csdn.net/jianhon...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。