MySQL TRUNCATE 與 DROP 命令之間的重要區別是什麼?


MySQL TRUNCATE 命令與 DROP 命令最主要的區別在於,TRUNCATE 命令不會破壞表結構,而 DROP 命令則會破壞表結構。

示例

mysql> Create table testing(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,Name Varchar(20));
Query OK, 0 rows affected (0.24 sec)

mysql> Insert into testing(Name) Values('Ram'),('Mohan'),('John');
Query OK, 3 rows affected (0.12 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> Select * from testing;
+----+-------+
| id | Name  |
+----+-------+
| 1  | Ram   |
| 2  | Mohan |
| 3  | John  |
+----+-------+
3 rows in set (0.00 sec)

現在,truncate 'testing' 表如下,儘管表結構仍保留在資料庫中,但主索引也會被初始化。

mysql> Truncate table testing;
Query OK, 0 rows affected (0.04 sec)

mysql> DESCRIBE testing;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.21 sec)

但當我們對錶應用 DROP 命令時,表結構也會從資料庫中刪除。

mysql> Drop table testing;
Query OK, 0 rows affected (0.08 sec)

mysql> DESCRIBE testing;
ERROR 1146 (42S02): Table 'query.testing' doesn't exist

更新於: 2020 年 6 月 20 日

237 次檢視

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.