0

Bom dia estou enfrentado o seguinte problema, criei 2 tabelas no banco, ao tentar criar uma fk em uma delas gerou o seguinte erro:#1215 - Cannot add foreign key constraint.

já verifiquei e engine e está como InnoDB, no código tbm não encontrei erro, já tinha feito o comando em outra tabela antes então tô um pouco perdido sobre a causa, segue os códigos das tabelas: esse primeira deu certo e está com aspas pq peguei o DDL dela.

CREATE TABLE `tb_fatura` (
  `id_fatura` varchar(40) NOT NULL,
  `data_fatura` date DEFAULT NULL,
  `user` int(11) NOT NULL,
  `valor_total_fatura` double(4,2) DEFAULT NULL,
  `status_fatura` varchar(20) DEFAULT NULL,
  KEY `fk_id_user` (`user`),
  CONSTRAINT `fk_id_user` FOREIGN KEY (`user`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

essa segunda não deu certo.

create table tb_fatura_item(
id int(11) primary key not null auto_increment,
id_fatura varchar(40) not null,
id_produto int(11)  not null,
quantidade int(11) not null,
constraint fk_id_fatura foreign key(id_fatura)
references tb_fatura(id_fatura)
)engine = InnoDB ;

Tabela users

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ip_address` varchar(15) NOT NULL,
  `username` varchar(250) NOT NULL,
  `password` varchar(255) NOT NULL,
  `salt` varchar(255) DEFAULT NULL,
  `email` varchar(100) NOT NULL,
  `activation_code` varchar(40) DEFAULT NULL,
  `forgotten_password_code` varchar(40) DEFAULT NULL,
  `forgotten_password_time` int(11) DEFAULT NULL,
  `remember_code` varchar(40) DEFAULT NULL,
  `created_on` int(11) NOT NULL,
  `last_login` int(11) DEFAULT NULL,
  `active` int(11) DEFAULT NULL,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `company` varchar(100) DEFAULT NULL,
  `phone` varchar(15) NOT NULL,
  `telefone_celular` varchar(15) DEFAULT NULL,
  `cpf_cnpj` varchar(18) DEFAULT NULL,
  `sexo` char(1) DEFAULT NULL,
  `data_nascimento` date DEFAULT NULL,
  `tipo_cliente` char(2) NOT NULL,
  `informacao_tributaria` char(1) DEFAULT NULL,
  `inscricao_estadual` varchar(12) DEFAULT NULL,
  `id_user_endereco` int(11) DEFAULT NULL,
  `identify_moodle` int(30) NOT NULL,
  `admin` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `IDX_LOGIN` (`email`,`password`),
  KEY `id_user_endereco` (`id_user_endereco`)
) ENGINE=InnoDB AUTO_INCREMENT=5460 DEFAULT CHARSET=latin1
4
  • Como está a tabela users? 3/10/2018 às 14:40
  • vou adicionar na pergunta. 3/10/2018 às 14:42
  • Atente a ordem de criação uma tabela que FK deve ser criada após a tabela ao qual faz referência. users tb_fatura tb_fatura_item
    – Motta
    3/10/2018 às 15:05
  • está exatamente nessa ordem, a primeira foi a users(que já existia em um projeto), ai criei tb_fatura e criei no fim a tb_fatura_item 3/10/2018 às 15:16

2 Respostas 2

2

O problema pode ser solucionado alterando a tabela :

'tb_fatura'

O campo que voce esta utilizando da tabela tb_fatura(id_fatura) para vincular na tabela tb_fatura_item não é chave primária(PK).

Assim funcionará:

CREATE TABLE `tb_fatura` (
  `id_fatura` varchar(40) primary key NOT NULL,
  `data_fatura` date DEFAULT NULL,
  `user` int(11) NOT NULL,
  `valor_total_fatura` double(4,2) DEFAULT NULL,
  `status_fatura` varchar(20) DEFAULT NULL,
  KEY `fk_id_user` (`user`),
  CONSTRAINT `fk_id_user` FOREIGN KEY (`user`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1
  • 1
    Vlw mano esse realmente era o problema. 3/10/2018 às 16:00
0

Só para constar tu pode criar uma váriavel fk_chave int e criar a ligação depois (acho mais fácil)

alter table tb1
add constraint fk_chave
foreign key (fk_chave)
references tb2 (pk_id)

abraço

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .