Mysql 插入带有外键的表时出现问题

标签 mysql

我对 MySql 还很陌生。 我在将带有外键的表插入到另一个表时遇到问题。下面提到的是父表和子表的语法。

===父====

 CREATE TABLE `userTable_temp` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `contactNum` varchar(64) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `contactNum` (`contactNum`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

====子=====

 CREATE TABLE `friendTable_temp` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userId` int(32) DEFAULT NULL,
  `friendId` int(32) DEFAULT NULL,
  `last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_test` (`userId`,`friendId`),
  KEY `friendId` (`friendId`),
  CONSTRAINT `friendTable_temp_ibfk_2` FOREIGN KEY (`friendId`) REFERENCES `userTable`   (`id`),
  CONSTRAINT `friendTable_temp_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `userTable` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1

我可以向friendTable_temp插入一些记录,但在第4次插入后,我总是收到以下错误

 "Cannot add or update a child row: a foreign key constraint fails (`contacts_db`.`friendTable_temp`, CONSTRAINT `friendTable_temp_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `userTable` (`id`))"

发生此问题时,我在 UserTable_temp 中有以下数据

mysql> select id, contactNum from userTable_temp;

+----+----------------+

|编号 |联系人数量 |

+----+----------------+

| 1 | 123455677 |

| 2 | 56465465464 |

| 3 | 567576567 |

| 4 | 1231231231 |

| 5 | 35453453454 |

| 6 | 45645645645 |

+----+----------------+

一组 6 行(0.00 秒)

当我尝试执行此操作时,发生上述错误

插入friendTable_temp(userId,friendId)值(6,1);

你能帮我找出我做错了什么吗?

注意: 插入friendTable_temp(userId,friendId)值(5,1);

查询正常,1 行受影响(0.00 秒)

谢谢

最佳答案

如下更改您的子表定义。

CREATE TABLE `friendTable_temp` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userId` int(32) DEFAULT NULL,
  `friendId` int(32) DEFAULT NULL,
  `last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_test` (`userId`,`friendId`),
  KEY `friendId` (`friendId`),
  CONSTRAINT `friendTable_temp_ibfk_2` FOREIGN KEY (`friendId`) REFERENCES `userTable_temp`   (`id`),
  CONSTRAINT `friendTable_temp_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `userTable_temp` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1

关于Mysql 插入带有外键的表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678708/

相关文章:

php - 搜索并替换 MySQL : nothing was replaced

MySQL Workbench EER 图创建

mysql - 授予来自任何主机(远程或本地)的访问权限

php - PHP 中是否有函数或命令可以解决数据未插入 SQL 数据库的问题?

php - Wordpress 按特定表中的值排序

php - 如何将父ID自动插入到另一个表中?

php - mysql 上的内部连接只适用于一列

php - 如何从数据库中获取插入前的最后一个插入ID

mysql - REQ.BODY 在 GET 调用中被传递为空

多个 FULLTEXT 索引上的 MySQL SELECT。结果极其缓慢