Cannot add or update a child row,表之间互相引用外键造成“死锁”。 Cannot add or update a child row,Cannot delete or update a parent row:
先建两张表:user和card,为了简单,都只有一个字段:id,让他们彼此成为对方的外键: mysql> create table user(id int primary key) character set utf8; mysql> create table card(id int primary key, constraint fk_user_id foreign key (id) references user(id))character set utf8; mysql> alter table user add constraint fk_card_id foreign key(id) references card(id); 此时,任何一张表都无法插入数据,也不能删除表。 mysql> drop table user; ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails 解决方法还是要删除外键约束,先通过:show create table user;找到外键约束的名字,再把约束删除: mysql> alter table user drop foreign key fk_card_id; 此时就可以向user插入数据了,card表也就可以删除了。
这个例子比较无聊,只是列出来,希望对遇到此问题的朋友有帮助。
create database employee; use employee;
create table dept( deptid char(13) not null primary key, depname varchar(14) not null) ENGINE=InnoDB DEFAULT CHARSET=latin1; insert into dept values(“12”,“开发部”); insert into dept values(“13”,“测试部”); insert into dept values(“11”,“财务部”);
create table empinfo( emp_id int not null primary key, ename char(13) not null, deptid char(13) not null, address varchar(20), foreign key(deptid) references dept(deptid)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into empinfo values(1,“wangtao”,‘12’,‘beijing’); insert into empinfo values(2,“zhangsan”,‘13’,‘上海’); insert into empinfo values(3,“zhangsan”,‘11’,‘上海’); insert into empinfo values(4,“zhangsan”,‘14’,‘sz’);
create table stumyinfo( stuid char(13) not null primary key, name varchar(14) not null, sex char, address varchar(40)) ENGINE=InnoDB DEFAULT CHARSET=latin1; insert into stumyinfo values(“12”,“sz”,‘female’,‘beijing’); insert into stumyinfo values(“13”,“cd”,‘man’,‘shanghai’); insert into stumyinfo values(“11”,“ce”,‘femal’,‘shenzhen’);
create table stuban( ban_id char(13) not null primary key, ban_name char(13) not null, stuid char(13) not null, foreign key(stuid) references stumyinfo(stuid)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into stuban values(“1003”,“001”, “13”); insert into stuban values(“1002”,“002”, “12”);
insert into stuban values(“1004”,“gx”, “11”); //报错,不存在这个11
FOREIGN KEY:将从表中的字段1作为外键的字段。
REFERENCES:映射到主表的字段2。
外键的使用需要满足下列的条件:(这里涉及到了InnoDB的概念)
两张表必须都是InnoDB表,并且它们没有临时表。注:InnoDB是数据库的引擎。MySQL常见引擎有两种:InnoDB和MyISAM,后者不支持外键。
建立外键关系的对应列必须具有相似的InnoDB内部数据类型。
建立外键关系的对应列必须建立了索引。
面试题:你的数据库用什么存储引擎?区别是?
答案:常见的有MyISAM和InnoDB。
MyISAM:不支持外键约束。不支持事务。对数据大批量导入时,它会边插入数据边建索引,所以为了提高执行效率, 应该先禁用索引,在完全导入后再开启索引。
InnoDB:支持外键约束,支持事务。对索引都是单独处理的,无需引用索引。