【问题标题】:Adding rows to table with foreign key constraint [MySQL]使用外键约束向表中添加行 [MySQL]
【发布时间】:2011-07-12 22:14:20
【问题描述】:

我有一个新表,它对旧的旧表具有外键约束。旧表中填充了大量数据,但是当我尝试向引用旧表中的一行的新表中添加一行时,我收到 Cannot add or update a child row: a foreign key constraint fails 错误。

如何将引用旧表中行的行添加到新表中?

编辑 这是我尝试过的两个查询:

mysql> select user_pk from users where username = 'test_user';
+---------+
| user_pk |
+---------+
|  123766 |
+---------+
1 row in set (0.00 sec)

mysql> insert into uservisit (user_id) values (123766);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test_database`.`uservisit`, CONSTRAINT `user_id_refs_user_pk_37c3999c` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_pk`))

我做错了吗?

【问题讨论】:

标签: mysql foreign-keys


【解决方案1】:

您可以像这样临时禁用外键检查:

SET foreign_key_checks = 0;
...
do updates
...
SET foreign_key_checks = 1;

最好确保在所有更新之后一切都按外键排序。

【讨论】:

    【解决方案2】:

    当您插入新行时,您放入具有外键的列中的值也必须存在于旧表的引用列中。

    也许如果你过去一些查询和示例数据,它会更容易提供帮助。

    【讨论】:

      【解决方案3】:

      如果您使用的是 5.5.13 之前的 MySQL 版本,您可能会遇到此错误:
      MySQL 5.5 foreign key constraint fails when foreign key exists

      【讨论】:

        猜你喜欢
        • 2014-06-01
        • 2017-09-01
        • 1970-01-01
        • 2013-03-10
        • 2021-11-05
        相关资源
        最近更新 更多