Mysql
無法添加或更新子項,外鍵錯誤
我對 MySQL 比較陌生。我試圖在關係數據庫中插入值。我知道我必須先插入父表,然後才能在子表中插入。假設我們有名為 STATE、COUNTRY 的表。
START TRANSACTION; INSERT INTO country (countryName, nationality,countryPrefix) SELECT * FROM (SELECT 'Togo' AS countryName, 'Togolese' AS nationality, '228' AS countryPrefix) AS tmp WHERE NOT EXISTS ( 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 WHERE NOT EXISTS ( SELECT stateName FROM state WHERE stateName = 'Region Maritime' ) LIMIT 1; COMMIT;
下圖是我遇到的錯誤的螢幕截圖。
此消息來自您嘗試插入連接表中不存在的數據
在你的情況下
您嘗試將12插入為國家/地區表中不存在的 County_id_contry。
所以你必須先在你的國家表中插入 12,然後再添加到國家表中