dongtie0929 2015-05-05 06:58
浏览 21

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

This insert command fails:

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');

It dies with this error message:

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`))

There are two tables, one called 'blogs' and one called 'posts'. 'blogs' has one column called 'blog' which serves as a primary key:

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

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

'posts' has a foreign key column called 'blog' which references the primary key in '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    |                |
+-----------+----------------+------+-----+---------+----------------+

What. The heck. Am I doing wrong? Many thanks. This error message does exist elsewhere but invariably they are more complex problems. I'm operating simply and directly from a mysql command line.

Note that the sql call is being made from a php mqsqli object $db->query($sql). The actual string doesn't include a semi-colon at the end.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 vscode问题请教
    • ¥50 切换TabTip键盘的输入法
    • ¥15 可否在不同线程中调用封装数据库操作的类
    • ¥15 微带串馈天线阵列每个阵元宽度计算
    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM