删除表

删除表是指删除数据库中已存在的表。删除表时,会删除表中的所有数据。

1、删除没有被关联的普通表

直接使用DROP  TABLE 语句可以删除没有被关联的普通表。

基本语法: DROP  TABLE  表名; 其中, 表名  参数为要删除的表的名称。

mysql> DROP TABLE example5; 删除example5

mysql> DROP TABLE example5,example6; 同时删除example5example6

2、删除被其他表关联的父表

mysql> DROP TABLE example1; 删除example1表时报错

ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails

结果显示失败,原因是有外键依赖于该表。因为之前创建 example4表依赖于example1表,example4表的外键 stu_id 依赖于example1 表的主键,example1 表是example4 表的父表。如果要删除example1 表,必须先去掉这种依赖关系。最简单直接的办法是,先删除子表example4 ,然后再删除父表example1 。但这样可能会影响子表的其他数据;另一种办法是,先删除子表的外键约束,然后再删除父表。这种办法,不会影响子表的其他数据,可以保证数据库的安全。其操作方法如下:

mysql> SHOW CREATE TABLE example4 \G 查看example4 表详细结构,关注外键约束。

*************************** 1. row ***************************

       Table: example4

Create Table: CREATE TABLE `example4` (

  `id` int(11) NOT NULL,

  `name` varchar(20) NOT NULL,

  `stu_id` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`),

  KEY `d_fk` (`stu_id`),

  CONSTRAINT `d_fk` FOREIGN KEY (`stu_id`) REFERENCES `example1` (`stu_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)

mysql> ALTER TABLE example4 DROP FOREIGN KEY d_fk; 删除example4 表的外键

Query OK, 0 rows affected (0.06 sec)

Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE example4 \G 再次查看example4 表详细结构,发现外键约束已经不存在了。

*************************** 1. row ***************************

       Table: example4

Create Table: CREATE TABLE `example4` (

  `id` int(11) NOT NULL,

  `name` varchar(20) NOT NULL,

  `stu_id` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`),

  KEY `d_fk` (`stu_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)

mysql> DROP TABLE example1; 直接删除example1

Query OK, 0 rows affected (0.06 sec)

mysql> DESC example1; 查询example1 表结构,报错提示example1 表不存在了,说明删除成功。

ERROR 1146 (42S02): Table 'test1.example1' doesn't exist

posted on 2019-07-21 15:08  凌乱的运维  阅读(1566)  评论(0编辑  收藏  举报

导航