Innodb

MariaDB:錯誤 1452 (23000):無法添加或更新子行:外鍵約束失敗

  • January 10, 2018

之前已經提出過這個問題,但建議的答案都不適用於我的情況。

問題:

由於外鍵違規,我無法將數據插入列中。但是,外鍵是有效的參考。

查詢失敗:

INSERT INTO `insert-table`(`not-important`, `foobar-id`) VALUES ('whatever', 'This exists in both tables');

錯誤:

錯誤 1452 (23000):無法添加或更新子行:外鍵約束失敗 ( mydb. insert-table, CONSTRAINT FK_foobarFOREIGN KEY ( foobar-id) REFERENCES foobar-table( foobar-id))

SELECT COUNT(1) FROM `foobar-table` WHERE `foobar-id` = 'This exists in both tables';
1

架構:

mysql> SHOW CREATE TABLE `insert-table`;
CREATE TABLE `insert-table` (
 `foobar-id` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL,
 `not-important` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`foobar-id`,`not-important`),
 CONSTRAINT `FK_foobar` FOREIGN KEY (`foobar-id`) REFERENCES `foobar-table` (`foobar-id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

mysql> SHOW CREATE TABLE `foobar-table`;
CREATE TABLE `foobar-table` (
 `foobar-id` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`foobar-id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

故障排除:

  1. 數據在那裡(沒有錯字,請參閱錯誤部分)
  2. 兩列具有相同的類型聲明(見上文)
  3. 使用的引擎已經是 InnoDB(一些網站建議切換到它)
  4. 我試圖從語句中刪除列名,以防一個錯誤使 MySQL 忽略它(因為它們都是同一類型)
  5. SELECT VERSION();5.6.10
  6. SHOW VARIABLES LIKE 'innodb_version';1.2.10
  7. 執行(具有PROCESS特權):
SHOW ENGINE INNODB STATUS;

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2018-01-10 15:24:39 2b1f59283700 Transaction:
TRANSACTION 17469656069, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
1 lock struct(s), heap size 376, 0 row lock(s)
MySQL thread id 147376, OS thread handle 0x2b1f59283700, query id 152047035 123.45.67.89 theDbUser update
INSERT INTO `insert-table` VALUES (‘This exists in the other table’, ‘whatever’)
Foreign key constraint fails for table `mydb`.`insert-table`:
,
CONSTRAINT `FK_foobar` FOREIGN KEY (`foobar-id`) REFERENCES `foobar-table` (`foobar-id`)
Trying to add to index `PRIMARY` tuple:
DATA TUPLE: 4 fields;
0: len=22; bufptr=0x2b2ea459a812; hex= 546869732065786973747320696e20626f7468207461626c6573; asc This exists in both tables;;
1: len=25; bufptr=0x2b2ea459ab0c; hex= 7768617465766572; asc whatever;;
2: len=6; bufptr=0x2b3a97464610; hex= 00041145cc05; asc    E  ;;
3: len=7; bufptr=0x2b3a97464618; hex= 00000000000000; asc        ;;

But the parent table `mydb`.`foobar-table`
or its .ibd file does not currently exist!

有關的:

顯然這不會發生在所有外鍵上,所以我們懷疑存在一些影響該外鍵的損壞。

解決方案是刪除並重新創建外鍵。

引用自:https://dba.stackexchange.com/questions/195102