在FK约束失败时-哪个键?

时间:2020-06-29 20:50:16

标签: mysql foreign-keys

再次遇到问题-手动检查数据并弄清楚,但这在很多情况下都是一个问题。情况是,您得到FK约束失败。您知道该错误是什么约束,因为它告诉您。

但是,它不会告诉您什么键使约束失败。为什么?!以及如何获取这些数据?我不必去挖掘数据来找出哪个键使约束失败。

1 个答案:

答案 0 :(得分:1)

   
//data.js    
function abc(){
let str  = "Turag"

function d(a){
let v = a.toUpperCase()
return v
}

const bcd = d(str)
return bcd

}
module.exports.captial = abc

//index.js

const getData = require('./data.js)
"user": getData.capital();
clg(user)

到目前为止,我们演示了可以使用两个外键插入到表中,并且如果我们使用引用表中存在的值,就可以了。

现在,使用不存在的值的另一行:

mysql> create table books (book_id int primary key);
mysql> insert into books set book_id = 22;

mysql> create table authors (author_id int primary key);
mysql> insert into authors set author_id = 44;

mysql> create table book_authors (book_id int, author_id int, 
  primary key (book_id, author_id), 
  foreign key (book_id) references books (book_id), 
  foreign key (author_id) references authors (author_id));

mysql> insert into book_authors values (22, 44);
Query OK, 1 row affected (0.01 sec)

该错误可准确告诉您哪个外键约束失败。

如果您想知道失败的,请查看innodb状态:

mysql> insert into book_authors values (22, 66);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
  ("test"."book_authors", CONSTRAINT "book_authors_ibfk_2" FOREIGN KEY ("author_id") 
  REFERENCES "authors" ("author_id"))

mysql> insert into book_authors values (33, 44);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 
  ("test"."book_authors", CONSTRAINT "book_authors_ibfk_1" FOREIGN KEY ("book_id") 
  REFERENCES "books" ("book_id"))

这很清楚地说明了这一点。

如果在向具有数据的表添加外键约束时遇到错误,并且问题在于子表中的某些值在被引用的表中没有匹配的值,您可以使用OUTER JOIN查找它们:

mysql> show engine innodb status\G
*************************** 1. row ***************************
  Type: InnoDB
  Name: 
Status: 
=====================================
2020-06-29 14:02:27 0x70000cf55000 INNODB MONITOR OUTPUT
=====================================
...
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2020-06-29 14:01:41 0x70000cf55000 Transaction:
TRANSACTION 557501, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 64, OS thread handle 123145519714304, query id 82122 localhost root update
insert into book_authors values (33, 44)
Foreign key constraint fails for table "test"."book_authors":
,
  CONSTRAINT "book_authors_ibfk_1" FOREIGN KEY ("book_id") REFERENCES "books" ("book_id")
Trying to add in child table, in index PRIMARY tuple:
DATA TUPLE: 4 fields;
 0: len 4; hex 80000021; asc    !;;
 1: len 4; hex 8000002c; asc    ,;;
 2: len 6; hex 0000000881bd; asc       ;;
 3: len 7; hex bb000001330110; asc     3  ;;

But in parent table "test"."books", in index PRIMARY,
the closest match we can find is record:
PHYSICAL RECORD: n_fields 3; compact format; info bits 0
 0: len 4; hex 80000016; asc     ;;
 1: len 6; hex 0000000881b8; asc       ;;
 2: len 7; hex b70000012f0110; asc     /  ;;

...
相关问题