MySQL ERROR 1215 (HY000): Cannot add foreign key constraint - mysql

I have looked everywhere about this error and seen plenty of examples and still i cant figure out whats wrong with my script. Im sorry if this is a common issue but searching about it hasnt helped me so far. Here goes the script:
CREATE DATABASE IF NOT EXISTS ventas;
USE ventas
CREATE TABLE TIENDAS (
nif varchar(10) not null,
nombre varchar(20),
direccion varchar(20),
poblacion varchar(20),
provincia varchar(20) check (provincia = upper(provincia)),
codpostal int(5),
PRIMARY KEY (nif)
) ENGINE=INNODB;
CREATE TABLE FABRICANTES (
cod_fabricante int(3) not null,
nombre varchar(15) check (nombre = upper(nombre)),
pais varchar(15) check (pais = upper(pais)),
PRIMARY KEY (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE ARTICULOS (
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
precio_venta int(4) unsigned CHECK (precio_venta > 0),
precio_costo int(4) unsigned CHECK (precio_costo > 0),
existencias int(5),
PRIMARY KEY (articulo,cod_fabricante,peso,categoria),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE PEDIDOS (
nif varchar(10) not null,
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
fecha_pedido date not null,
unidades_pedidas int(4),
PRIMARY KEY (nif,articulo,cod_fabricante,peso,categoria,fecha_pedido),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante),
FOREIGN KEY (articulo) references ARTICULOS (articulo) ON DELETE CASCADE,
FOREIGN KEY (cod_fabricante) references ARTICULOS (cod_fabricante) ON DELETE CASCADE,
FOREIGN KEY (peso) references ARTICULOS (peso) ON DELETE CASCADE,
FOREIGN KEY (categoria) references ARTICULOS (categoria) ON DELETE CASCADE,
FOREIGN KEY (nif) references TIENDAS (nif)
) ENGINE=INNODB;
Thanks a lot for your help.

In your ARTICULOS table, you have multiple columns as primary key .i.e. articulo,cod_fabricante,peso,categoria. In the PEDIDOS table, you are referring a foreign key articulo to ARTUCULOS table's articulo column. Which I think is wrong.
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns

Related

Cannot add foreign key here?

So I'm trying to create tables and I can't for the life of me understand why i keep getting and error saying "Cannot add foreign key to constraint".
The types are the same, the parent is a primary key, and they're NULLness is the same.
The problem is in the line in the create table for CDSingers where it says:
foreign key (track_num) references CDTracks (track_num),
(it's near the end)
It's the only table that won't be created and it's because of this line.
Please help.
(some of the other tables have been ommitted since they aren't connected)
create table CD
(
num int NOT NULL,
producer varchar(100) NOT NULL,
cd_number varchar(100) NOT NULL,
title varchar(100) NOT NULL,
type varchar(100) ,
band_name varchar(100) ,
production_date DATE NOT NULL,
price double CHECK (price >= 0),
foreign key (type) references MusicType (type),
foreign key (band_name) references Band (band_name),
primary key (num),
unique (producer, cd_number)
);
create table CDTracks
(
num int NOT NULL,
track_num int NOT NULL,
song_name varchar(100) NOT NULL,
minute int NOT NULL,
foreign key (num) references CD (num),
primary key (num, track_num)
);
create table Singer
(
id int NOT NULL,
singer_firstname varchar(100) NOT NULL,
singer_lastname varchar(100) NOT NULL,
primary key (id)
);
create table CDSingers
(
num int NOT NULL,
track_num int NOT NULL,
singer_id int NOT NULL,
foreign key (num) references CDTracks (num),
foreign key (track_num) references CDTracks (track_num),
foreign key (singer_id) references Singer (id),
primary key (num, track_num, singer_id)
);
You declare composite foreign keys like this:
foreign key (num, track_num) references CDTracks (num, track_num),

SQL - Foreign key constraint is incorrectly formed

I don't know what's the problem in this code... I verified all columns names and data types but this not work
CREATE TABLE empleado (
tipo_dni VARCHAR(50) NOT NULL,
nro_dni INT NOT NULL,
nombre VARCHAR(50) NOT NULL,
apellido VARCHAR(50) NOT NULL,
direccion VARCHAR(50) NOT NULL,
telefono INT NOT NULL,
id_ciudad INT NOT NULL,
PRIMARY KEY (tipo_dni , nro_dni)
);
CREATE TABLE director (
tipo_dni VARCHAR(50) NOT NULL,
nro_dni INT NOT NULL,
PRIMARY KEY (tipo_dni, nro_dni),
FOREIGN KEY (tipo_dni)
REFERENCES empleado (tipo_dni),
FOREIGN KEY (nro_dni)
REFERENCES empleado (nro_dni)
);
ERROR
#1005 - Can't create table `tpfinal`.`director` (errno: 150 "Foreign key constraint is incorrectly formed")
Any idea ?
You primary key is:
PRIMARY KEY (tipo_dni , nro_dni)
This is a composite primary key. The foreign key reference should be composite as well:
FOREIGN KEY (tipo_dni, nro_dni)
REFERENCES empleado (tipo_dni, nro_dni)

MySql foreign key constraint issue

I am trying to develop a university database and am stuck with few tables throwing a constraint error. I have tried various workarounds:
1. Checking my eninge status. It's INNODB across all tables.
2. On Update On Delete parameters(although I am not sure if I am doing that correctly).
3. Checking the NULL reference and the data types. Foreign keys referred to have the same data types as the primary key in the table which is making the reference.
This is my query:
CREATE TABLE Faculty (
FacNo CHAR(11) NOT NULL,
FacFirstName VARCHAR(30) NOT NULL,
FacLastName VARCHAR(30) NOT NULL,
FacCity VARCHAR(30) NOT NULL,
FacState CHAR(2) NOT NULL,
FacDept CHAR(6) NULL,
FacRank CHAR(4) NULL,
FacSalary DECIMAL(10,2) NULL,
FacSupervisor CHAR(11) NOT NULL,
FacHireDate DATETIME NULL,
FacZipCode CHAR(10) NOT NULL,
CONSTRAINT FacultyPK PRIMARY KEY (FacNo),
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty
ON DELETE NO ACTION
ON UPDATE NO ACTION )engine = innodb;
This is the OFFERING table making the reference:
CREATE TABLE Offering (
OfferNo INTEGER NOT NULL,
CourseNo CHAR(6) NOT NULL,
OffTerm CHAR(6) NOT NULL,
OffYear INTEGER NOT NULL,
OffLocation VARCHAR(30) NULL,
OffTime VARCHAR(10) NULL,
FacNo CHAR(11) NOT NULL,
OffDays CHAR(4) NULL,
CONSTRAINT OfferingPK PRIMARY KEY (OfferNo),
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course,
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty )ENGINE = INNODB;
Your foreign key references are lacking columns:
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty(Facno)
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course(CourseNo),
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty(FacNo)
Here is a SQL Fiddle. It doesn't have the CourseNo foreign key, because that isn't defined in the question.

Cannot add foreign key constraint 2

im try create a foreign key to Poblacion, on table cp_cliente, but i cant, i take the error "cannot add foreign key", im try change the name, but i cant. If i delete Poblacion foreign key the script work fine.
CREATE TABLE provincias (
Cod_provincia INT(2) PRIMARY KEY,
Provincia VARCHAR(50) NOT NULL
);
CREATE TABLE cp_cliente (
CP CHAR(5),
Cod_provincia INT(2),
Poblacion VARCHAR(70),
PRIMARY KEY (CP, Poblacion, Cod_provincia),
FOREIGN KEY (Cod_provincia) REFERENCES provincias(Cod_provincia) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE cliente (
DNI CHAR(9) PRIMARY KEY,
Nombre VARCHAR(20) NOT NULL,
Apellidos VARCHAR(20) NOT NULL,
Direccion VARCHAR(50) NOT NULL,
CP CHAR(5),
Cod_provincia INT(2),
Poblacion VARCHAR(70),
FOREIGN KEY (CP) REFERENCES cp_cliente(CP) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (Cod_provincia) REFERENCES cp_cliente(Cod_provincia) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (Poblacion) REFERENCES cp_cliente(Poblacion) ON DELETE SET NULL ON UPDATE CASCADE
);
What is the problem? I can't see him :(
Sorry my bad english.

Can two columns from one table have a foreign key to the same column in another table?

I have two tables in a database, Person and Pet.
CREATE TABLE Person (
id INT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner)
REFERENCES Person(id),
FOREIGN KEY (current_owner)
REFERENCES Person(id)
)
I am trying to reference the previous owner, and the current owner for each pet. I have also tried
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id, id)
)
and
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id)
)
but I get the following error:
Error Code: 1215. Cannot add foreign key constraint
Is this even possible to accomplish? Or would I have to create some sort of bridge table to accommodate this?
Please try the following:
CREATE TABLE IF NOT EXISTS `pet` (
`id` int(11) NOT NULL,
`original_owner` int(11) NOT NULL,
`current_owner` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `origin` (`original_owner`),
KEY `current` (`current_owner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `pet`
ADD CONSTRAINT `pet_ibfk_2` FOREIGN KEY (`current_owner`) REFERENCES `person` (`id`),
ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`original_owner`) REFERENCES `person` (`id`);
The problem was the order I had the tables defined in the script. I had Pet come before Person. Once I put Person above Pet it worked fine. The example in the question was written from my head, as I didn't have the actual code handy when I posted it.