ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

后端 未结 3 479
抹茶落季
抹茶落季 2021-01-04 09:11

When I execute the following SQL command:

INSERT INTO test_usershosts (RID,userid,hid,Usr,Pass) 
VALUES (NULL,1,1,\"user\",\"pass\");

I\'m

3条回答
  •  既然无缘
    2021-01-04 09:29

    The reason why you are getting that exception is because you are inserting a record on table test_usershosts which the value of the userID is not present on table test_users. Same as the value of hid is not also present on table test_hosts.

    Table test_usershosts is dependent on tables: test_users and test_hosts. So be sure that when inserting records on table test_usershosts, the values for hid and userid already exists on the parent tables: test_users and test_hosts.

    Try executing this query and surely it will be inserted.

    INSERT INTO test_usershosts (RID,userid,hid,Usr,Pass) 
    VALUES (NULL,1120,30,'user','pass');
    
    • SQLFiddle Demo

    I see that AUTO_INCREMENT option on tables: test_users and test_hosts, are not needed since you are supplying values on every query you are executing on the two tables.

提交回复
热议问题