方法一 delete from <表名>
:
# 此方法刪除表內(nèi)全部數(shù)據(jù)后咱枉,返回刪除數(shù)據(jù)的數(shù)量
# 如果表內(nèi)有自增字段,它的起始值保留當(dāng)前數(shù)值
mysql> delete from course;
Query OK, 60 rows affected (0.02 sec)
方法二 truncate table <表名>
:
# 如果表內(nèi)有自增字段,它的起始值恢復(fù)為 1
# 刪除速度比 delete 快
# 當(dāng)表的主鍵有外鍵約束時(shí)兢哭,無法刪除數(shù)據(jù)以躯,會報(bào)類似下面的錯誤(delete 方法無此問題):
mysql> truncate table user;
ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key ...
# 因?yàn)?course 類設(shè)置了外鍵約束
# 執(zhí)行 show create table course\G 查看 course 表的全部信息
mysql> show create table course\G
*************************** 1. row ***************************
Table: course
Create Table: CREATE TABLE `course` (
`create_at` datetime DEFAULT NULL,
`update_at` datetime DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`author_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ix_course_name` (`name`),
KEY `author_id` (`author_id`),
CONSTRAINT `course_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `user` (`id`)
ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
# 執(zhí)行此命令刪除 course 表的外鍵約束
mysql> alter table course drop foreign key course_ibfk_1;
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
# 然后就可以用 truncate 刪除 user 表的全部數(shù)據(jù)了
mysql> truncate table user;
Query OK, 0 rows affected (0.00 sec)
# 最后執(zhí)行此命令重新設(shè)置外鍵即可
mysql> alter table course add constraint foreign key course(author_id) references
user(id);
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0