MySQL TRUNCATE和DELETE命令有什么区别?
众所周知,TRUNCATE将删除所有行,而不会从数据库中删除表的结构。借助DELETE命令可以完成从表中删除所有行的相同工作。但是,两个命令之间对PRIMARY KEY AUTO_INCREMENT的重新初始化有很大的不同。
假定定义了具有PRIMARY KEY CONSTRAINT的AUTO_INCREMENT列,那么在使用DELETE命令删除所有行时不会重新初始化表,即,在输入新行时,AUTO_INCREMENT编号将在最后插入的行之后开始。相反,在使用TRUNCATE时,该表将像新创建的表一样重新初始化。这意味着在使用TRUNCATE命令并插入新行后,AUTO_INCREMENT编号将从1开始。
示例
以下示例将演示上述概念-
mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));mysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');
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;
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');
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;
mysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');
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命令有什么区别? 的全部内容, 来源链接: utcz.com/z/343426.html