1
votes

EDIT:

My problem was because of the tables used diffrent engines. Table Chart used MyISAM and Chartdata used InnoDB.


i have a very simple DB model but for some reason i cant get the Foreign Key to work. I have created the DB with Mysql Workbench and i have two rows in the 'Chart' table with id 3 and 4. When i try to add a row in chartdata i get this error:

INSERT INTO `charts`.`Chartdata` (

`idChartdata` ,
`param1` ,
`param2` ,
`Chart_id` 
)
VALUES (
NULL , '2012-01-10 05:00:00', '58', '3'
) 

#1452 - Cannot add or update a child row: a foreign key constraint fails (charts.Chartdata, CONSTRAINTfk_Chartdata_ChartFOREIGN KEY (Chart_id) REFERENCESChart(idChart) ON DELETE CASCADE ON UPDATE CASCADE)

I am sure that the foreign key exists, and i have tried to recreate the tables severeal times (with minor changes).

Link to DB model: http://i.stack.imgur.com/qKZlh.png

This is a SQL dump from PhpMyAdmin:

CREATE TABLE IF NOT EXISTS `Chartdata` (

idChartdata int(11) NOT NULL AUTO_INCREMENT, param1 varchar(500) DEFAULT NULL, param2 varchar(500) DEFAULT NULL, Chart_id int(11) NOT NULL, PRIMARY KEY (idChartdata,Chart_id), KEY fk_Chartdata_Chart (Chart_id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

ALTER TABLE Chartdata ADD CONSTRAINT fk_Chartdata_Chart FOREIGN KEY (Chart_id) REFERENCES Chart (idChart) ON DELETE CASCADE ON UPDATE CASCADE;

3
Could you include the failing SQL INSERT statement in your question?Joachim Isaksson
I have added it to the question.Lasse Vabe Rolstad
My problem was because of the tables used diffrent engines. Table Chart used MyISAM and Chartdata used InnoDB.Lasse Vabe Rolstad

3 Answers

2
votes

My problem was because of the tables used diffrent engines. Table Chart used MyISAM and Chartdata used InnoDB.

0
votes

remove the NULL in your INSERT query since the column idChartdata is set to Auto_Increment and try again.

INSERT INTO `charts`.`Chartdata`(`param1` ,`param2` ,`Chart_id`)
VALUES ('2012-01-10 05:00:00', '58', '3') 
0
votes

You are trying to add a row to chartdata, with Chart_id = 3. Is there a chart with idChart = 3? Trie to add a chart with id = 3 first, then perform your query.

[edit] Nvm, you solved it already. :D