I can not get a foreign key in PHPMYADMIN

1

I have my bank already created in phpmyadmin, there are two tables, payments and students. I've seen several tutorials and read various ways how to put a foreign key ( fk_alunos ) of student_id in my payments table, nothing works.

Table pagamentos

CREATE TABLE IF NOT EXISTS 'horus'.'pagamentos' (
  'id' INT(11) NOT NULL AUTO_INCREMENT,
  'situacao_aluno' VARCHAR(100) NOT NULL,
  'validade_plano' VARCHAR(15) NOT NULL,
  'planos' VARCHAR(100) NOT NULL,
  'vencimento' VARCHAR(50) NOT NULL,
  'cpf_amigo' VARCHAR(50) NOT NULL,
  'forma_pagamento' VARCHAR(100) NOT NULL,
  'data_matricula' VARCHAR(20) NOT NULL,
  'numero_documento' VARCHAR(50) NOT NULL,
  'data_documento' VARCHAR(15) NOT NULL,
  'valor' VARCHAR(6) NOT NULL,
  'status' VARCHAR(100) NOT NULL,
  'status_mensalidade' VARCHAR(100) NOT NULL,
  'alunos_id' INT(11) NOT NULL )

Table alunos

CREATE TABLE IF NOT EXISTS 'horus'.'alunos' (
 'id' INT(11) NOT NULL AUTO_INCREMENT,
 'nome' VARCHAR(100) NOT NULL,
 'cpf' VARCHAR(15) NOT NULL,
 'rg' VARCHAR(15) NOT NULL,
 'nascimento' VARCHAR(50) NOT NULL,
 'sexo' VARCHAR(100) NOT NULL,
 'fone' VARCHAR(15) NOT NULL,
 'email' VARCHAR(100) NOT NULL,
 'endereco' VARCHAR(100) NOT NULL,
 'bairro' VARCHAR(100) NOT NULL,
 'cep' VARCHAR(10) NOT NULL,
 'estado' VARCHAR(50) NOT NULL,
 'cidade' VARCHAR(100) NOT NULL,
  PRIMARY KEY ('id'),
  UNIQUE INDEX 'cpf' ('cpf' ASC),
  UNIQUE INDEX 'rg' ('rg' ASC))
  ENGINE = InnoDB
 AUTO_INCREMENT = 2
 DEFAULT CHARACTER SET = latin1;

In the payments table I put another field with id_alunos In the indexes of the payments table I added the name of the key fk_alunos , column id_pagamentos .

After that, when I try to run the code " ALTER TABLE pagamentos ADD CONSTRAINT fk_alunos FOREIGN KEY(id_alunos) REFERENCES alunos (id_alunos) ", it only brings me errors saying:

  

"# 1452 - Can not add or update child row: a foreign key constraint   fails ( horus . #sql-32d0_181 , CONSTRAINT id_alunos FOREIGN KEY   ( id_alunos ) REFERENCES alunos ( id_alunos )) "

I tried to make the relationship model through the workbench and then import it into phpmyadmin, but even then the foreign key does not appear.

    
asked by anonymous 18.09.2018 / 16:42

2 answers

2

Simple: REFERENCES alunos (id_alunos) is incorrect because the alunos table does not have a column named id_alunos . I believe the correct one would be REFERENCES alunos (id) .

Another detail is that you have alunos_id in your payments table while you reference the id_alunos column that does not exist in your FK.

    
18.09.2018 / 17:02
0

I was able to find the solution! Thank you all ...

The error was because my phpmyadmin was not updated, not even the drawing of the foreign key appeared .... I ended up remounting the table payments again by writing in SQL and mentioning the foreign key right there!

Thank you all.

    
19.09.2018 / 14:26