mysql清空表中truncate與delete都是刪除表的操作,但還是有些許不同。
delete和truncate區(qū)別如下:
一、靈活性:delete可以條件刪除數(shù)據(jù),而truncate只能刪除表的所有數(shù)據(jù);
delete * from table_name;
delete from table_test where ...
truncate table table_test
注 : truncate操作中的table可以省略,delete操作中的*可以省略
delete是一條一條刪除記錄的,配合事件(transaction)和回滾(rollback)可以找回?cái)?shù)據(jù),且自增(auto_increment)不會(huì)重置。 truncate則是直接刪除整個(gè)表,再重新創(chuàng)建一個(gè)一模一樣的新表,auto_increment會(huì)被重置,且數(shù)據(jù)無(wú)法找回。
二、效率:delete效率低于truncate,delete是一行一行地刪除,truncate會(huì)重建表結(jié)構(gòu),
三、事務(wù):truncate是DDL語(yǔ)句,需要drop權(quán)限,因此會(huì)隱式提交,不能夠rollback;delete是DML語(yǔ)句,可以使用rollback回滾。
四、觸發(fā)器:truncate 不能觸發(fā)任何Delete觸發(fā)器;而delete可以觸發(fā)delete觸發(fā)器。
1> truncate 是整體刪除 (速度較快),delete是逐條刪除 (速度較慢) 2> truncate 不寫(xiě)服務(wù)器 log,delete 寫(xiě)服務(wù)器 log,也就是 truncate 效率比 delete高的原因 3> truncate 不激活trigger (觸發(fā)器),但是會(huì)重置Identity (標(biāo)識(shí)列、自增字段),相當(dāng)于自增列會(huì)被置為初始值,又重新從1開(kāi)始記錄,而不是接著原來(lái)的 ID數(shù)。而 delete 刪除以后,identity 依舊是接著被刪除的最近的那一條記錄ID加1后進(jìn)行記錄。如果只需刪除表中的部分記錄,只能使用 DELETE語(yǔ)句配合 where條件
mysql> select * from students_bak; +-----+----------+--------+---------+ | sid | sname | gender | dept_id | +-----+----------+--------+---------+ | 101 | zhangsan | male | 10 | | 1 | aa | 1 | 1 | +-----+----------+--------+---------+ 2 rows in set (0.00 sec) mysql> truncate table students_bak; Query OK, 0 rows affected (0.16 sec) mysql> select * from students_bak; Empty set (0.00 sec) mysql> set autocommit=off; Query OK, 0 rows affected (0.01 sec) mysql> select * from students3; +-----+-------+--------+---------+--------+ | sid | sname | gender | dept_id | sname2 | +-----+-------+--------+---------+--------+ | 100 | NULL | 1 | 1 | NULL | +-----+-------+--------+---------+--------+ 1 row in set (0.01 sec) mysql> truncate table students3; Query OK, 0 rows affected (0.06 sec) mysql> rollback; Query OK, 0 rows affected (0.00 sec) mysql> select * from students3; Empty set (0.00 sec) mysql> delete from students; Query OK, 5 rows affected (0.00 sec) mysql> select * from students; Empty set (0.00 sec) mysql> rollback; Query OK, 0 rows affected (0.07 sec) mysql> select * from students; +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 1 | aa | 3 | 1 | | 4 | cc | 3 | 1 | | 5 | dd | 1 | 2 | | 6 | aac | 1 | 1 | | 10 | a | 1 | 1 | +-----+-------+--------+---------+ 5 rows in set (0.00 sec)
如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答?。?點(diǎn)擊進(jìn)入論壇