在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...