Error Code: 1215. Cannot add foreign key constraint - mysql

I'm trying to create a software for a gym but I'm getting this error and I don't know why, I've trying for hours but nothing
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
PRIMARY KEY (IdSocio)
) ENGINE=INNODB;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
PRIMARY KEY (IdTipos)
) ENGINE = INNODB;
CREATE TABLE productos (
IdProducto INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Descripcion VARCHAR (100),
Costo_Individual DECIMAL(6,2) NOT NULL,
Precio_venta DECIMAL(6,2) NOT NULL,
Estado BOOL NOT NULL,
Cantidad_Inicial INT NOT NULL,
Cantidad_actual INT NOT NULL,
PRIMARY KEY(IdProducto)
) ENGINE = INNODB;
Error Code: 1215. Cannot add foreign key constraint
I'm getting this error for this tables
CREATE TABLE membresia(
IdMembresia INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Tipo VARCHAR(30) NOT NULL,
Fecha_Inicio DATE NOT NULL,
Fecha_Vencimiento DATE NOT NULL,
Inscripcion BOOL NOT NULL,
Estado_membresia VARCHAR(15) NOT NULL,
Fecha_modificacion DATE NOT NULL,
Total DECIMAL(6,2) NOT NULL,
Nota VARCHAR(100),
Fecha_Nota DATE,
PRIMARY KEY (IdMembresia),
CONSTRAINT IdSocio FOREIGN KEY (Nombre)
REFERENCES Socios (Nombre),
CONSTRAINT IdTipos FOREIGN KEY (Tipo,Total)
REFERENCES tipos (Tipo,Precio)
) ENGINE = INNODB;
CREATE TABLE ventas (
IdVenta INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Fecha_venta DATE NOT NULL,
cantidad INT NOT NULL,
Total DECIMAL(8,2),
Fecha_Modificacion DATE NOT NULL,
Nota VARCHAR (100),
PRIMARY KEY (IdVenta),
CONSTRAINT IdProducto FOREIGN KEY (Producto)
REFERENCES productos(Producto)
) ENGINE = INNODB;

This will get you over an initial hurdle. Though I doubt you really want an FK on a price but I don't know the translation into your mother tongue.
You need indexes on the referenced tables for the columns looked up in FK's.
create schema dbtest_xyz;
use dbtest_xyz;
-- drop table Socios;
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
PRIMARY KEY (IdSocio),
key(Nombre) -- ADDED *******************************
) ENGINE=INNODB;
-- drop table tipos;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
PRIMARY KEY (IdTipos),
key(Tipo), -- ADDED *******************************
key(Precio) -- ADDED *******************************
) ENGINE = INNODB;
-- drop table productos;
CREATE TABLE productos (
IdProducto INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Descripcion VARCHAR (100),
Costo_Individual DECIMAL(6,2) NOT NULL,
Precio_venta DECIMAL(6,2) NOT NULL,
Estado BOOL NOT NULL,
Cantidad_Inicial INT NOT NULL,
Cantidad_actual INT NOT NULL,
PRIMARY KEY(IdProducto),
key(Producto) -- ADDED *******************************
) ENGINE = INNODB;
CREATE TABLE membresia(
IdMembresia INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Tipo VARCHAR(30) NOT NULL,
Fecha_Inicio DATE NOT NULL,
Fecha_Vencimiento DATE NOT NULL,
Inscripcion BOOL NOT NULL,
Estado_membresia VARCHAR(15) NOT NULL,
Fecha_modificacion DATE NOT NULL,
Total DECIMAL(6,2) NOT NULL,
Nota VARCHAR(100),
Fecha_Nota DATE,
PRIMARY KEY (IdMembresia),
CONSTRAINT IdSocio FOREIGN KEY (Nombre)
REFERENCES Socios (Nombre),
CONSTRAINT IdTipos FOREIGN KEY (Tipo)
REFERENCES tipos (Tipo),
CONSTRAINT IdMembresia FOREIGN KEY (Total)
REFERENCES tipos (Precio)
) ENGINE = INNODB;
CREATE TABLE ventas (
IdVenta INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Fecha_venta DATE NOT NULL,
cantidad INT NOT NULL,
Total DECIMAL(8,2),
Fecha_Modificacion DATE NOT NULL,
Nota VARCHAR (100),
PRIMARY KEY (IdVenta),
CONSTRAINT IdProducto FOREIGN KEY (Producto)
REFERENCES productos(Producto)
) ENGINE = INNODB;
-- Cleanup:
drop schema dbtest_xyz;
Mysql Manual Page on Foreign Keys
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Note, the reason I have the drop tables above some tables is that it is wise to have them in place while one iteratively attempts the creations. When the FK creations fail, one often (almost always) has to re-jigger the referenced and referencing tables.

Your first 2 tables should be as per below, means referenced fields should be indexed.
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
KEY idx_Nombre(Nombre),
PRIMARY KEY (IdSocio)
) ENGINE=INNODB;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
KEY idx_tipo_precio(Tipo,Precio),
PRIMARY KEY (IdTipos)
) ENGINE = INNODB;

In case this may help someone else one day, I had this issue yet none of the existing solutions helped - columns were same type, same collation, etc.
However, I had a stored generated column in the table containing the foreign key that referenced that key column, and for some reason this broke the foreign key generation. Removing the generated column and using a trigger instead fixed it.

Related

ERROR IN SQL COMMAND / FOREIGN KEY PROBLEM

I was training to create a table in SQL, but I got this message
The ideia of the code is this one:
/* criando as tabelas */
CREATE TABLE CLIENTES (
IDCLIENTE INT PRIMARY KEY AUTO_INCREMENT,
CLIENTE VARCHAR(10)NOT NULL,
ESTADO CHAR(2) NOT NULL,
SEXO ENUM ('M','F') NOT NULL,
STATUS VARCHAR (10)
);
CREATE TABLE VENDEDORES (
IDVENDEDOR INT PRIMARY KEY AUTO_INCREMENT,
NOME VARCHAR (20) NOT NULL
);
CREATE TABLE PRODUTOS (
IDPRODUTO INT PRIMARY KEY AUTO_INCREMENT,
PRODUTO VARCHAR (20) NOT NULL,
PRECO FLOAT(10,2) NOT NULL
);
CREATE TABLE VENDAS (
IDVENDA INT PRIMARY KEY AUTO_INCREMENT,
TOTAL INT NOT NULL,
ID_VENDEDOR INT ,
FOREIGN KEY (ID_VENDEDOR)
REFERENCES VENDEDORES(IDVENDEDOR)
ID_CLIENTE INT,
FOREIGN KEY (ID_CLIENTE)
REFERENCES CLIENTES(IDCLIENTE)
);
CREATE TABLE ITENS_VENDAS(
ID_VENDA INT NOT NULL,
ID_PRODUTO INT NOT NULL,
FOREIGN KEY ID_VENDA
REFERENCES VENDAS(IDVENDA)
FOREIGN KEY ID_PRODUTO
REFERENCES PRODUTOS(IDPRODUTO)
QUANTIDADE INT NOT NULL,
VALOR_UNITARIO FLOAT(10,2) NOT NULL,
VALOR_TOTAL FLOAT(10,2) NOT NULL,
DESCONTO FLOAT(10,2) NOT NULL
);
I was creating that from this idea of this flowchart:
I understand that I'm making a mistake in the foreign key part
but i can't understand what is wrong.
P.S: I'am new at programing in sql.
You have some syntax error
CREATE TABLE CLIENTES (
IDCLIENTE INT PRIMARY KEY AUTO_INCREMENT,
CLIENTE VARCHAR(10)NOT NULL,
ESTADO CHAR(2) NOT NULL,
SEXO ENUM ('M','F') NOT NULL,
STATUS VARCHAR (10)
);
✓
CREATE TABLE VENDEDORES (
IDVENDEDOR INT PRIMARY KEY AUTO_INCREMENT,
NOME VARCHAR (20) NOT NULL
);
✓
CREATE TABLE PRODUTOS (
IDPRODUTO INT PRIMARY KEY AUTO_INCREMENT,
PRODUTO VARCHAR (20) NOT NULL,
PRECO FLOAT(10,2) NOT NULL
);
✓
CREATE TABLE VENDAS (
IDVENDA INT PRIMARY KEY AUTO_INCREMENT,
TOTAL INT NOT NULL,
ID_VENDEDOR INT ,
FOREIGN KEY (ID_VENDEDOR)
REFERENCES VENDEDORES(IDVENDEDOR),
ID_CLIENTE INT,
FOREIGN KEY (ID_CLIENTE)
REFERENCES CLIENTES(IDCLIENTE)
);
✓
CREATE TABLE ITENS_VENDAS(
ID_VENDA INT NOT NULL,
ID_PRODUTO INT NOT NULL,
FOREIGN KEY (ID_VENDA)
REFERENCES VENDAS(IDVENDA),
FOREIGN KEY (ID_PRODUTO)
REFERENCES PRODUTOS(IDPRODUTO),
QUANTIDADE INT NOT NULL,
VALOR_UNITARIO FLOAT(10,2) NOT NULL,
VALOR_TOTAL FLOAT(10,2) NOT NULL,
DESCONTO FLOAT(10,2) NOT NULL
);
✓
db<>fiddle here

Error Code 1824 - Failed to open the referenced table

I'm trying to create my DB project on MySQL, and when I tried to add foreign keys, it show the error code 1824 on all of the tables I'm trying to create. My code is this:
create table cliente (
id_cliente varchar(20) not null primary key,
nome varchar(50) unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
id_cartao_cliente int not null,
cod_encomenda_cliente int not null,
constraint fk_cartao foreign key (id_cartao_cliente) references cartao_credito(id_cartao),
constraint fk_encomenda foreign key (cod_encomenda_cliente) references encomenda(cod_encomenda)
) engine = innodb;
create table cartao_credito (
id_cartao int not null primary key,
num_cartao varchar(20) not null,
nome_cartao varchar(30) not null,
mes_validade varchar(2) not null,
ano_validade year,
id_cliente_cartao varchar(20) not null,
constraint fk_cliente foreign key (id_cliente_cartao) references cliente(id_cliente)
) engine = innodb;
create table Encomenda (
cod_encomenda int not null primary key,
tipo varchar(15) not null,
valor_encomenda varchar(10) not null,
local_destino varchar(20) not null,
id_destinatario_encomenda varchar(20) not null,
constraint fk_destinatario foreign key (id_destinatario_encomenda) references destinatario(id_destinatario)
) engine = innodb;
create table movimentacao (
id varchar(50) not null primary key,
local_movimentacao varchar(50) not null,
descricao varchar(30) not null,
data_movimentacao date not null,
hora_movimentacao time not null,
cod_encomenda_movimentacao int not null,
id_entregador_movimentacao varchar(20) not null,
foreign key (cod_encomenda_movimentacao) references encomenda(cod_encomenda),
foreign key (id_entregador_movimentacao) references entregador(id_entregador)
) engine = innodb;
create table entregador (
id_entregador varchar(20) not null primary key,
nome varchar(50) unique not null,
placa_veiculo varchar(10) not null,
tipo_veiculo varchar(15) not null,
cod_encomenda_entregador varchar(50) not null,
id_destinatario_entregador varchar(20) not null,
foreign key (cod_encomenda_entregador) references encomenda(cod_encomenda),
foreign key (id_destinatario_entregador) references destinatario(id_destinatario)
) engine = innodb;
create table destinatario (
id_destinatario varchar(20) not null primary key,
nome varchar(50) not null unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
cod_encomenda_destinatario int not null,
foreign key (cod_encomenda_destinatario) references encomenda(cod_encomenda)
) engine = innodb;
I need help with this code please.
P.S.: all of the columns are written in Portuguese
MySQL error code 1824 is "Failure to open referenced table."
I believe you are running into trouble because of the order you are creating in. I see that "Encomenda" does not have a foreign key, and may be a good place to start your creation.
Your design is wrong. Because when an entity in cliente refer to cartao_credito it means there is a (1 to N) relation between these two table. So no need to refer cartao_credito to cliente again. If you need an N to N relationship use a bridge (a new table) between them and use two 1 to N relationship.
In your design all tables refer to each other mutually. For example in two first table you need just one foreign key to join these two tables not two foreign key.

MySQL Error 1215 creating foreign key

My question is about MySQL, I keep getting an error (Error 1215: Cannot add Foreign key Constraint) while trying to forward engineer a schema to a db server, I've got two parent tables:
CREATE TABLE IF NOT EXISTS alunos (
idAluno INT NOT NULL AUTO_INCREMENT,
NomeAluno VARCHAR(100) NOT NULL,
nifAluno VARCHAR(15) NOT NULL,
moradaAluno VARCHAR(255) NOT NULL,
telefoneAluno VARCHAR(9) NOT NULL,
emailAluno VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
PRIMARY KEY(idAluno, nifAluno)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS cursos (
idCurso INT NOT NULL AUTO_INCREMENT,
nomeCurso VARCHAR(50) NOT NULL,
horas INT NOT NULL,
PRIMARY KEY(idCurso, nomeCurso)
) ENGINE=INNODB;
And this is my child table:
CREATE TABLE IF NOT EXISTS inscritos (
id INT NOT NULL AUTO_INCREMENT,
Nome VARCHAR(100) NOT NULL,
Morada VARCHAR(255) NOT NULL,
Naturalidade VARCHAR(45) NOT NULL,
NIF VARCHAR(15) NOT NULL,
email VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
Telefone VARCHAR(9) NOT NULL,
Curso VARCHAR(50) NOT NULL,
Horas INT NOT NULL,
Inicio DATE NOT NULL,
Validade DATE NOT NULL,
Atividade VARCHAR(45) NOT NULL,
PRIMARY KEY(id),
INDEX(NIF),
INDEX(Curso),
FOREIGN KEY(NIF)
REFERENCES alunos(nifAluno)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(Curso)
REFERENCES cursos(nomeCurso)
ON UPDATE RESTRICT ON DELETE RESTRICT
) ENGINE=INNODB;
I've looked through the code over and over and I can't seem to find the error when assigning the foreign keys.
Thanks in advance.
Because, NIF and Curso aren't primary/unique key in inscritos table. Creating index doesn't mean you are creating key on same column. So, just for your information. The referenced columns in the Parent table must be the left-most columns of a key. Best if the key is PRIMARY KEY or UNIQUE KEY.
As #Bill commented, he has an answer where he has prepared a checklist, you may refer to make sure, you won't get any other error.

MySQL error code 1005 / errno: 150

I'm using a XAMPP 5.6.19-0 as a MySQL Database server and managing via MySQL Workbench (Mac OS 10.11.3). I'm trying to create some tables, with foreign keys, and im getting this error:
Error Code: 1005. Can't create table imobiliaria24h.proprietario (errno: 150 "Foreign key constraint is incorrectly formed")
This is the code I'm trying to use:
CREATE TABLE IF NOT EXISTS PROPRIETARIO (
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS IMOVEL(
ENDERECO VARCHAR(100) NOT NULL,
TIPO ENUM('ALUGUEL', 'VENDA'),
INQUILINO_CPF INT,
PROPRIETARIO_CPF INT,
VALOR_ALUGUEL_PRECOVENDA INT NOT NULL,
NUM_QUARTOS INT NOT NULL,
METRAGEM INT NOT NULL,
NUM_BANHEIROS INT NOT NULL,
VALOR_CONDOMINIO INT NOT NULL,
IDADE INT NOT NULL,
HORA_REGISTRO TIME NOT NULL,
PRIMARY KEY(ENDERECO),
FOREIGN KEY (INQUILINO_CPF) REFERENCES INQUILINO(CPF),
FOREIGN KEY (PROPRIETARIO_CPF) REFERENCES PROPRIETARIO(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS INQUILINO(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
FIADOR BOOLEAN NOT NULL,
INADIMPLENCIA INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS CORRETOR(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
ANOS_CASA SMALLINT NOT NULL,
TRABALHA_FDS BOOLEAN NOT NULL,
TRABALHA_NOITE BOOLEAN NOT NULL,
PRIMARY KEY (CPF)
)ENGINE=InnoDB;
The interesting thing is that, if I create the table separately, only the ones that references each other, for example, I created first PROPRIETARIO and CORRETOR, second INQUILINO, and at last IMOVEL, and this way everything worked. I'm not understanding why I'm getting the error creating them all together in a "single command".
Are you running that exact script? If so, it looks like you're trying to create the foreign keys before you've actually crated the tables they're referencing.
Try changing the order in which you build them.
CREATE TABLE IF NOT EXISTS CORRETOR(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
ANOS_CASA SMALLINT NOT NULL,
TRABALHA_FDS BOOLEAN NOT NULL,
TRABALHA_NOITE BOOLEAN NOT NULL,
PRIMARY KEY (CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS PROPRIETARIO (
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS INQUILINO(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
FIADOR BOOLEAN NOT NULL,
INADIMPLENCIA INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS IMOVEL(
ENDERECO VARCHAR(100) NOT NULL,
TIPO ENUM('ALUGUEL', 'VENDA'),
INQUILINO_CPF INT,
PROPRIETARIO_CPF INT,
VALOR_ALUGUEL_PRECOVENDA INT NOT NULL,
NUM_QUARTOS INT NOT NULL,
METRAGEM INT NOT NULL,
NUM_BANHEIROS INT NOT NULL,
VALOR_CONDOMINIO INT NOT NULL,
IDADE INT NOT NULL,
HORA_REGISTRO TIME NOT NULL,
PRIMARY KEY(ENDERECO),
FOREIGN KEY (INQUILINO_CPF) REFERENCES INQUILINO(CPF),
FOREIGN KEY (PROPRIETARIO_CPF) REFERENCES PROPRIETARIO(CPF)
)ENGINE=InnoDB;

Documentation #1005 - Can't create table 'comparein' (errno: 150)

Where is the problem? i am trying to create the table comparein using the composed primary key from the table Episodi but there should be a problem that i can t see..
the primary key from the table is a combination of "numero" and "titolo_episodio"
create table Autori(
id_autore int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15) not null,
nome_arte varchar (15)
) ENGINE=InnoDB;
create table Serie(
nome varchar(25) primary key,
id_autore int(6),
descrizione varchar(400),
FOREIGN KEY (id_autore)REFERENCES Autori(id_autore)
) ENGINE=InnoDB;
create table Episodi(
titolo_episodio varchar(25) not null,
numero int not null,
durata time not null,
data_trasmissione date not null,
nome_serie varchar(25),
PRIMARY KEY(titolo_episodio,numero),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Personaggi(
id_pers int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15),
nazionalita varchar (15),
nome_serie varchar(25),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Utenti(
nickname varchar(15) primary key,
nazionalita varchar(15) not null,
mail varchar(25) not null,
pwd varchar(15) not null,
amministratore bool default 0 not null
) ENGINE=InnoDB;
create table Generi(
genere varchar(15) primary key
) ENGINE=InnoDB;
create table comparein(
id_pers int not null,
numero int not null,
titolo_episodio varchar(25),
FOREIGN KEY (id_pers)REFERENCES Personaggi(id_pers),
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio),
primary key(id_pers,numero,titolo_episodio)
) ENGINE=InnoDB;
I think you need to reference the PK columns in the same order as the primary key was defined. So instead of
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio)
use
FOREIGN KEY (titolo_episodio, numero) REFERENCES Episodi(titolo_episodio, numero)
SQLFiddle: http://sqlfiddle.com/#!2/363bd