Mysql - Error performing INSERT with FOREIGN KEY

Asked

Viewed 150 times

1

Hello, when performing an insert in the database Mysql returns the following error:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`zabbix`.`tb_hosts`, CONSTRAINT `tb_hosts_ibfk_1` FO
REIGN KEY (`fk_hostname_grupo`) REFERENCES `tb_grupos` (`hostname_grupo`)) 

What’s the mistake? Thanks in advance!

Code used:

CREATE TABLE tb_grupos(
  id_grupo int(50) NOT NULL,
  hostname_grupo varchar(50) NOT NULL PRIMARY KEY);

CREATE TABLE tb_hosts (
  id_host int(50) NOT NULL PRIMARY KEY,
  hostname varchar(50) NOT NULL,
  fk_hostname_grupo varchar(50) NOT NULL,
  FOREIGN KEY (fk_hostname_grupo) REFERENCES tb_grupos(hostname_grupo));

  CREATE TABLE tb_monitoramento (
  problemas varchar(50) NOT NULL PRIMARY KEY,
  tempo int(50) DEFAULT NULL,
  fk2_hostname_grupo varchar(50) NOT NULL,
  FOREIGN KEY (fk2_hostname_grupo) REFERENCES tb_grupos(hostname_grupo));

CREATE TABLE tb_eventos (
  id_evento int(50) NOT NULL,
  eventos varchar(50) NOT NULL,
  tempo int(50) NOT NULL,
  trigger_or_network int(3) NOT NULL,
  ok_or_problema_or_desconhecido int(3) NOT NULL,
  fk3_hostname_grupo varchar(50) NOT NULL PRIMARY KEY,
  FOREIGN KEY (fk3_hostname_grupo) REFERENCES tb_grupos(hostname_grupo));

  insert into tb_grupos values("2","usergroup");
  insert into tb_hosts values("3","user", 1);
  • Excuse me but this error log does not match this code. Look here error-free.

  • yes, but when running Mysql installed on my machine has error, I am using Deepin 15.10, it may be some bug in the distro?

1 answer

1


You are using hostname_grupo as PK, and in insert is adding an item in the tb_hosts.hostname whose value does not exist in the referenced table.

  • @userlimer to separate one case from the other, create another ask for it. This helps anyone who in the future has the same problem. :)

  • beauty thank you!

  • And if the problem was this, signal as the answer. If not, post the answer and then signal as correct. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.