增加外键时候的一个小错误
生活随笔
收集整理的這篇文章主要介紹了
增加外键时候的一个小错误
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
已知表 student
mysql> desc student; +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | stu_id | int | NO | PRI | NULL | auto_increment | | num | int | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | varchar(4) | YES | | NULL | | | birthday | datetime | YES | | NULL | | | address | varchar(56) | YES | | NULL | | +----------+-------------+------+-----+---------+----------------+ 6 rows in set (0.00 sec)?已知表t1
mysql> desc t1; +--------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+---------+------+-----+---------+-------+ | stu_id | int | YES | | NULL | | | name | char(3) | YES | | NULL | | | grade | tinyint | YES | | NULL | | +--------+---------+------+-----+---------+-------+ 3 rows in set (0.00 sec)增加外鍵:
alter table t1 add constraint f_key foreign key(stu_id) references student(stu_id);?報錯
mysql> alter table t1-> add constraint f_key foreign key(stu_id) references student(stu_id); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`school`.`#sql-116c_8`, CONSTRAINT `f_key` FOREIGN KEY (`stu_id`) REFERENCES `student` (`stu_id`))?查看表student 和t1
mysql> select * from t1; +--------+--------+-------+ | stu_id | name | grade | +--------+--------+-------+ | 1 | 喬國忠 | 3 | +--------+--------+-------+ 1 row in set (0.00 sec)mysql> select * from student; Empty set (0.00 sec)發(fā)現(xiàn)原因,表格t1 中的內(nèi)容和student中不對稱 ——表格t1中多一行內(nèi)容,而這一行student中沒有,所以報錯。
修改方法,刪除t1中多余的行或者增加student中對應(yīng)的行(stu_id為 1的行):
mysql> insert into student values(1,12345,'robert','m',20200323121212,'neimeng province'); Query OK, 1 row affected (0.01 sec)mysql> select * from student; +--------+-------+--------+------+---------------------+------------------+ | stu_id | num | name | sex | birthday | address | +--------+-------+--------+------+---------------------+------------------+ | 1 | 12345 | robert | m | 2020-03-23 12:12:12 | neimeng province | +--------+-------+--------+------+---------------------+------------------+ 1 row in set (0.00 sec)接下來,等到兩個表格中的stu_id中內(nèi)容對稱之后,執(zhí)行
mysql> alter table t1-> add constraint-> fff_key-> foreign key(stu_id) references student(stu_id); Query OK, 1 row affected (0.10 sec) Records: 1 Duplicates: 0 Warnings: 0成功了。
mysql> alter table t1-> add constraint fff_key foreign key(stu_id) references student(stu_id); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`school`.`#sql-116c_8`, CONSTRAINT `fff_key` FOREIGN KEY (`stu_id`) REFERENCES `student` (`stu_id`))錯誤原因:表中內(nèi)容不對應(yīng)。?
?
總結(jié)
以上是生活随笔為你收集整理的增加外键时候的一个小错误的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: list 用法总结2
- 下一篇: vector中的圆括号和花括号