简体   繁体   中英

MySql: Error Code: 1452

Here is my erd diagram of my tables...

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. Which means you have to provide a value for users_id which corresponds to an id in your users table.

If we assume you want to add an item for the user with id 1, your statement should look like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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