1.删除没有被关联的表
2.删除被其他表关联的主表
(1)删除没有被关联的表
语法:
drop table [if exists] 表1,表2,...表n;
如果要删除的表不存在,报错:"ERROR 1051(42S02): Unknown table '表名'
",添加IF EXISTS
可以顺利执行,但是会warning。
【例】删除数据表tb_dept2,SQL语句如下:
mysql> drop table if exists tb_dept2;
Query OK, 0 rows affected (0.07 sec)
(2)删除被其他表关联的主表
数据表之间存在外键关联的情况下,不能直接删除父表。若要单独删除父表,需要将关联的表的外键约束条件取消,下面讲解这种方法。
第一步:首先创建两个关联表tb_dept2和tb_emp:
mysql> create table tb_dept2
-> (
-> id int(11) primary key,
-> name varchar(22),
-> location varchar(50)
-> );
Query OK, 0 rows affected (0.13 sec)
mysql> create table tb_emp
-> (
-> id int(11) primary key,
-> name varchar(25),
-> deptID int(11),
-> salary float,
-> constraint fk_emp_dept foreign key (deptID) references tb_dept2(id)
-> );
Query OK, 0 rows affected (0.13 sec)
查看tb_emp的外键约束:
Create Table: CREATE TABLE `tb_emp` (
`id` int(11) NOT NULL,
`name` varchar(25) DEFAULT NULL,
`deptID` int(11) DEFAULT NULL,
`salary` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_emp_dept` (`deptID`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`deptID`) REFERENCES `tb_dept2` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.06 sec)
可以看到tb_emp为子表,具有名称为fk_enp_dept的外键约束;tb_dept2为父表,其主键id被子表tb_emp所关联。
第二步:删除被数据表tb_dept2关联的数据表tb_dept2:
直接删除会报错:
mysql> drop table tb_dept2;
ERROR 3730 (HY000): Cannot drop table 'tb_dept2' referenced by a foreign key constraint 'fk_emp_dept' on table 'tb_emp'.
应该首先解除关联子表tb_emp的外键约束,然后再删除,SQL语句如下:
mysql> alter table tb_emp drop foreign key fk_emp_dept;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> drop table tb_dept2;
Query OK, 0 rows affected (0.07 sec)
此时已经删除成功了。
来源:https://blog.csdn.net/weixin_43691058/article/details/99492050