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
, CONSTRAINTid_alunos
FOREIGN KEY (id_alunos
) REFERENCESalunos
(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.