Can’t add or update child, Foreign Key Error

Posted on

Question :

enter image description hereI’m kinder new in MySQL.
I was trying to insert value in a relational database.
I know that i have to insert in parent table before doing it in child table.
Assume we have tables named STATE, COUNTRY.

INSERT INTO country (countryName, nationality,countryPrefix)
SELECT * FROM (SELECT 'Togo' AS countryName, 'Togolese' AS nationality, '228' AS countryPrefix) AS tmp
    SELECT countryName FROM country WHERE countryName = 'Togo'
) LIMIT 1;
SELECT country.idcountry FROM country WHERE country.countryName = 'Togo';
INSERT INTO state (stateName, country_idcountry)
SELECT * FROM (SELECT 'Region Maritime' AS stateName, '12' AS country_idcountry) AS tmp
    SELECT stateName FROM state WHERE stateName = 'Region Maritime'
) LIMIT 1;

Below image is the screenshot of the error i encountered.

enter image description here

Answer :

this message comes of you trying to insert data, that are not exist in the connected tabel

In you case

Your try to insert 12 as county_id_contry which doesn’t exist in the table country.

So you have to insert 12 in your country table first, before you add to the state table

Leave a Reply

Your email address will not be published. Required fields are marked *