简体   繁体   English

MySql:错误代码:1452

[英]MySql: Error Code: 1452

Here is my erd diagram of my tables... 这是我的桌子的erd图...

I am trying to INSERT VALUES into my items table using the following code... 我正在尝试使用以下代码将值插入项目表中...

INSERT INTO items (item, addedby, updated_at, created_at) VALUES ("one","two" NOW(), NOW())

I am getting the following error... 我收到以下错误...

11:15:53    INSERT INTO items (item, addedby, updated_at, created_at) VALUES ("one", "two", NOW(), NOW())   Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`wishlist`.`items`, CONSTRAINT `fk_items_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) 0.046 sec

Whats going on!? 这是怎么回事!?

When you add relations in MySQL Workbench, it creates foreign key constraints automatically. 在MySQL Workbench中添加关系时,它会自动创建外键约束。 Which means you have to provide a value for users_id which corresponds to an id in your users table. 这意味着您必须为users_id提供一个值,该值对应于users表中的一个id。

If we assume you want to add an item for the user with id 1, your statement should look like this: 如果我们假设您要为ID为1的用户添加一个项目,则您的声明应如下所示:

INSERT INTO items (item, addedby, updated_at, created_at, users_id) VALUES ("one","two" NOW(), NOW(), 1)

For further information look up referential integrity . 有关更多信息,请查找参照完整性

If you have just added the user and don't know his id because it's an AUTO_INCREMENT value, you can use LAST_INSERT_ID() to retrieve it. 如果您刚刚添加了用户并且因为它是一个AUTO_INCREMENT值而不知道其ID,则可以使用LAST_INSERT_ID()来检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM