MYSQL错误1452(23000):无法添加或更新子行:外键约束失败另一个问题

时间:2014-03-20 21:24:40

标签: mysql

我刚刚在几分钟之前发布了另一个问题并解决了问题,现在又有了另一个问题我不知道这个问题出在哪里。

mysql> describe customers;

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(10)      | NO   | PRI | NULL    | auto_increment |
| name      | varchar(255) | NO   |     | NULL    |                |
| email     | varchar(255) | NO   |     | NULL    |                |
| states_id | tinyint(3)   | NO   | MUL | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

mysql> insert into customers (name, email, states_id) values('Thomas', 't@email.com', 2);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`crm`.`customers`, CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`states_id`) REFERENCES `states` (`id`) ON UPDATE CASCADE)

mysql> insert into customers (name, email, states_id) values('Thomas', 't@email.com', 2);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`crm`.`customers`, CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`states_id`) REFERENCES `states` (`id`) ON UPDATE CASCADE)

mysql> describe states
    -> ;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | tinyint(3)   | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

1 个答案:

答案 0 :(得分:0)

的结果是什么?
SELECT * FROM states;

我打赌你没有在该表中有ID 2的条目。在您可以在另一个表中插入相关条目之前,引用的ID必须存在于该表中。