语句大概就是这样创建了emp表和advice表,advice表里的emp_id对外键到emp表里的id项,为什么emp表还能被删除 create table emp ( id int primary key, name varchar(32) not null ); create table advice ( emp_id int not null, content text not null, foreign key(emp_id) references emp(id) ); drop table emp; 运行结果:
参考技术A当某表被外键约束关联时,InnoDB不允许你删除该表,除非你执行了SET foreign_key_checks = 0命令。当LOAD DATA和ALTER TABLE操作时设置foreign_key_checks为0是很有用的,可以避免外键检查提高效率。 foreign_key_checks从mysql 3.23.52 and 4.0.3开始时可用的。
1mysql> insert into dage(name) values(‘铜锣湾‘); 2Query OK, 1 row affected (0.01 sec) 3mysql> select * from dage; 4+----+--------+ 5| id | name | 6+----+--------+ 7| 1 | 铜锣湾 | 8+----+--------+ 91 row in set (0.00 sec)
插入个小弟:
1mysql> insert into xiaodi(dage_id,name) values(1,‘铜锣湾_小弟A‘); 2Query OK, 1 row affected (0.02 sec) 3 4mysql> select * from xiaodi; 5+----+---------+--------------+ 6| id | dage_id | name | 7+----+---------+--------------+ 8| 1 | 1 | 铜锣湾_小弟A | 9+----+---------+--------------+
把大哥删除:
1mysql> delete from dage where id=1; 2ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`bstar/xiaodi`, CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`))
提示:不行呀,有约束的,大哥下面还有小弟,可不能扔下我们不管呀!
插入一个新的小弟:
1mysql> insert into xiaodi(dage_id,name) values(2,‘旺角_小弟A‘); 2ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bstar/xiaodi`, CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`)) 3
1mysql> delete from dage where id=1; 2Query OK, 1 row affected (0.01 sec) 3 4mysql> select * from dage; 5Empty set (0.01 sec) 6 7mysql> select * from xiaodi; 8Empty set (0.00 sec)