Problem in foreign key creation

Asked

Viewed 288 times

3

I’m having trouble creating a foreign key from these tables:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Code:

ALTER TABLE `tb_permissao_view` ADD  CONSTRAINT
`fk_tb_permissao_view_tb_sistema_pagina`
FOREIGN KEY (`cd_pagina`)
REFERENCES `tb_sistema_pagina` (`cd_pagina`);

Error:

ALTER TABLE `tb_permissao_view` ADD CONSTRAINT
`fk_tb_permissao_view_tb_sistema_pagina` FOREIGN KEY (`cd_pagina`)     
REFERENCES `tb_sistema_pagina` (`cd_pagina`)
Error Code: 1452. Cannot add or update a child row: 
a foreign key constraint fails (`portal`.`#sql-4ee_f`, CONSTRAINT 
`fk_tb_permissao_view_tb_sistema_pagina` FOREIGN KEY (`cd_pagina`) REFERENCES 
`tb_sistema_pagina` (`cd_pagina`)) 
  • tb_permissao_view has recorded data already or both are empty?

  • Yes, both tables have records.

  • There are probably values in tb_permissao_view in the column cd_pagina that do not exist in cd_pagina of the reference table tb_sistema_pagina. Check if there really are divergent values in these two columns.

  • 2

    Thank you very much brother!

1 answer

2


As stated in the comments, the error is triggered because there are values in the column cd_pagina table tb_permissao_view that do not exist in the column cd_pagina reference table for foreign key tb_sistema_pagina.

All values in column foreign key should exist in the column to which it is being referenced, and as you said there is already data in both tables, check in the column cd_pagina table tb_permissao_view there is no divergent data from the table to which it has a foreign key relation (in this case the table tb_sistema_pagina).

References:

ERROR 1452: Cannot add or update a Child Row: a Foreign key Constraint fails

Browser other questions tagged

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