mysql清空表数据的两种方式和区别

MySQL中删除数据有两种方式:mysql

  1. truncate(截短)属于粗暴型的清空
  2. delete属于精细化的删除

删除操做

若是你须要清空表里的全部数据,下面两种都可:sql

delete from tablename;
truncate table tablename;

而若是你只是删除一部分数据,就只能使用deleteapache

delete from tablename where case1 and case2;

区别

在精细化的删除部分数据时,只能使用delete
而清空全部表数据时,二者都可,此时这两种方式有必定的区别:服务器

返回值

truncate返回值为0,而delete会返回被删除的记录数.net

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语句作判断,所以效率低。code

操做日志

truncate不写服务器日志,没法恢复。
delete会写服务器日志。blog

触发器

truncate不激活触发器,delete会激活触发器。get

参考资料

  1. MySQL 清空表(truncate)与删除表中数据(delete) 详解:https://blog.csdn.net/chenshu...
  2. MySQL中删除数据的两种方法:https://blog.csdn.net/apache6...
  3. 清空某个mysql表中全部内容:https://blog.csdn.net/jianhon...
相关文章
相关标签/搜索