$ mysqli查询失败,外键约束失败

时间:2015-05-05 06:58:35

标签: php mysql

此插入命令失败:

INSERT INTO posts (id, headline, content, post_date, blog) VALUES (default, 'Birds 
in Nepal are being Messed With', 'Have you heard about this? There are birds in 
the country of Nepal that are sitting around minding their own business, when out 
of nowhere they are getting messed with. Messed with!', curdate(), 'cost');

它因此错误消息而死:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint 
fails (`allanwebdev`.`posts`, CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`blog`) 
REFERENCES `blogs` (`blog`))

有两个表,一个称为“博客”,另一个称为“帖子”。 'blogs'有一个名为'blog'的专栏作为主键:

DESCRIBE BLOGS;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| blog  | varchar(10) | NO   | PRI |         |       |
+-------+-------------+------+-----+---------+-------+

SELECT * FROM BLOGS;
+----------+
| blog     |
+----------+
| code     |
| politics |
| satire   |
+----------+

'posts'有一个名为'blog'的外键列,它引用了'blogs'中的主键。

DESCRIBE POSTS;
+-----------+----------------+------+-----+---------+----------------+
| Field     | Type           | Null | Key | Default | Extra          |
+-----------+----------------+------+-----+---------+----------------+
| id        | int(11)        | NO   | PRI | NULL    | auto_increment |
| headline  | varchar(60)    | YES  |     | NULL    |                |
| post_date | date           | YES  |     | NULL    |                |
| content   | varchar(64000) | YES  |     | NULL    |                |
| blog      | varchar(10)    | YES  | MUL | NULL    |                |
+-----------+----------------+------+-----+---------+----------------+

什么。哎呀。我做错了吗?非常感谢。此错误消息确实存在于其他地方,但总是会出现更复杂的问题。我只是直接从mysql命令行操作。

请注意,sql调用是从php mqsqli对象$ db->查询($ sql)进行的。实际字符串末尾不包括分号。

0 个答案:

没有答案