Search code examples
mysqlmysql-error-1452

MySQL Workbench error 1452


I've trying to create a foreign key from a table to another, using the tools that MySQL Workbench provides, but all that I get is this error:

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`mediacom`.`#sql-758_4`, CONSTRAINT `med_agente_ibfk_1` FOREIGN KEY (`id_agenzia`) REFERENCES `med_agenzia` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `mediacom`.`med_agente` 
ADD CONSTRAINT `med_agente_ibfk_1`
  FOREIGN KEY (`id_agenzia`)
  REFERENCES `mediacom`.`med_agenzia` (`id`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION

The thing that confuses me the most is the line mediacom.#sql-758_4, since the real query that I use is :

ALTER TABLE `mediacom`.`med_agente` 
ADD INDEX `med_agente_ibfk_1_idx` (`id_agenzia` ASC)  COMMENT '';
ALTER TABLE `mediacom`.`med_agente` 
ADD CONSTRAINT `med_agente_ibfk_1`
  FOREIGN KEY (`id_agenzia`)
  REFERENCES `mediacom`.`med_agenzia` (`id`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

The index is inserted fine but the rest is ignored, why?

This is the med_agente table

CREATE TABLE `med_agente` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(225) DEFAULT NULL,
  `cognome` varchar(225) DEFAULT NULL,
  `disabilitato` tinyint(1) DEFAULT NULL,
  `mod_time` datetime DEFAULT NULL,
  `mod_user` varchar(255) DEFAULT NULL,
  `codmobile` decimal(13,0) DEFAULT NULL,
  `codfisso` decimal(13,0) DEFAULT NULL,
  `id_agenzia` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `med_agente_ibfk_1_idx` (`id_agenzia`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

And this is med_agenzia

CREATE TABLE `med_agenzia` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ragSociale` varchar(255) NOT NULL,
  `descrizione` varchar(255) DEFAULT NULL,
  `indirizzo` varchar(255) DEFAULT NULL,
  `citta` varchar(255) DEFAULT NULL,
  `CAP` int(11) DEFAULT NULL,
  `provincia` varchar(255) DEFAULT NULL,
  `tel` int(11) DEFAULT NULL,
  `mail` varchar(255) DEFAULT NULL,
  `codFiscale` varchar(255) DEFAULT NULL,
  `pIVA` varchar(255) DEFAULT NULL,
  `id_azsuper` int(11) DEFAULT NULL,
  `disabilitato` tinyint(1) DEFAULT NULL,
  `mod_time` datetime DEFAULT NULL,
  `mod_user` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

where's the problem???


Solution

  • Before you run your query

    Run this :

     SET FOREIGN_KEY_CHECKS=0;
    

    Then set it to 1

    SET FOREIGN_KEY_CHECKS=1;
    

    after you run your Alter query.