众所周知,TRUNCATE 将删除所有行,而不从数据库中删除表的结构。可以借助 DELETE 命令完成相同的工作,从表中删除所有行。但这两个命令之间的 PRIMARY KEY AUTO_INCRMENT 重新初始化存在显着差异。
假设一列定义了具有 PRIMARY KEY CONSTRAINT 的 AUTO_INCRMENT,那么在使用 DELETE 命令删除所有行时将不会重新初始化初始化表,即在输入新行时,AUTO_INCREMENT 数字将从最后插入的行之后开始。相反,在使用 TRUNCATE 时,表将像新创建的表一样重新初始化。这意味着使用 TRUNCATE 命令并插入新行后,AUTO_INCRMENT 数字将从 1 开始。
示例
以下示例将演示上述概念 -
mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.15 sec)
mysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
| 4 | Yashraj |
| 5 | Manak |
+----+---------+
5 rows in set (0.00 sec)
mysql> Delete from testing where id >=4;
Query OK, 2 rows affected (0.04 sec)
mysql> Select * from testing;
+----+--------+
| Id | Name |
+----+--------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
+----+--------+
3 rows in set (0.00 sec)
mysql> Insert into testing(Name) values('Harshit'),('Lovkesh');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
| 6 | Harshit |
| 7 | Lovkesh |
+----+---------+
5 rows in set (0.00 sec)
mysql> Truncate table testing;
Query OK, 0 rows affected (0.10 sec)
mysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');
Query OK, 4 rows affected (0.11 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Harshit |
| 2 | Lovkesh |
| 3 | Ram |
| 4 | Gaurav |
+----+---------+
4 rows in set (0.00 sec)
登录后复制
以上就是MySQL TRUNCATE 和 DELETE 命令有什么区别?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!