1
I have my bank already created in phpmyadmin, are two tables, payments and students.
I have seen several tutorials and read various ways of how to put a foreign key (fk_alunos
) id_students 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 being the id_alunos
In the indexes of the payments table I added the name of the key fk_alunos
, spine id_pagamentos
.
After that, when I try to execute the code "ALTER TABLE pagamentos ADD CONSTRAINT fk_alunos FOREIGN KEY(id_alunos) REFERENCES alunos (id_alunos)
", only brings me mistakes saying :
" #1452 - Cannot add or update a Child Row: a Foreign key Constraint fails (
horus
.#sql-32d0_181
, CONSTRAINTid_alunos
FOREIGN KEY (id_alunos
) REFERENCESalunos
(id_alunos
)) "
I tried to make relationship model by Workbench to then import into phpmyadmin, but not even so the foreign key appears.
And are there already records in the tables? Can the foreign key be null? Ask the question the definition of both tables, please.
– Woss
already exist yes records...
– Verônica Emschermann