【问题标题】:error altering table, adding constraint foreign key getting error "Cannot add or update a child row"更改表时出错,添加约束外键获取错误“无法添加或更新子行”
【发布时间】:2014-01-01 17:48:05
【问题描述】:
mysql> DESCRIBE questions;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(255)     | NO   | PRI | NULL    | auto_increment |
| question | varchar(255) | NO   |     | NULL    |                |
| type     | char(1)      | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE answers;  
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(255)     | NO   | PRI | NULL    | auto_increment |
| answer       | varchar(255) | NO   |     | NULL    |                |
| questionid   | int(255)     | NO   |     | NULL    |                |
| questions_id | int(255)     | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

我正在使用这个语句:

ALTER TABLE 答案添加外键(questions_id)参考问题(id);

但我得到这个错误:

错误 1452 (23000):无法添加或更新子行:外键约束失败 (surveydb.#sql-df_32, CONSTRAINT #sql-df_32_ibfk_1 FOREIGN KEY (questions_id) REFERENCES questions (id )) 到您的 MySQL 服务器版本,以便在第 1 行的“DESCREBE questions”附近使用正确的语法

【问题讨论】:

  • 这些表中是否有数据?

标签: mysql foreign-keys


【解决方案1】:

answers.questions_id 中至少有一个数据值不会出现在 questions.id 中。

这是我的意思的一个例子:

mysql> create table a ( id int primary key);

mysql> create table b ( aid int );

mysql> insert into a values (123);

mysql> insert into b values (123), (456);

mysql> alter table b add foreign key (aid) references a(id);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint 
fails (`test`.`#sql-3dab_e5c`, CONSTRAINT `#sql-3dab_e5c_ibfk_1` FOREIGN KEY
(`aid`) REFERENCES `a` (`id`))

您可以使用它来确认存在不匹配的值:

SELECT COUNT(*)
FROM answers AS a
LEFT OUTER JOIN questions AS q ON a.questions_id = q.id
WHERE q.id IS NULL

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2022-12-10
    • 2015-02-04
    • 2013-06-11
    • 2019-03-29
    相关资源
    最近更新 更多