Mysql, cannot add foreign key constraint - mysql

Why does this:
Create table Kaart (
aantal_geel int not null,
aantal_rood int not null,
Primary key (aantal_geel, aantal_rood));
Create table Wedstrijd (
datum date not null,
aantal_geel int not null,
aantal_rood int not null,
Primary key (datum),
Foreign key (aantal_geel) REFERENCES kaart(aantal_geel),
Foreign key (aantal_rood) REFERENCES kaart(aantal_rood));
Gives: Error Code: 1215. Cannot add foreign key constraint

You need to reference the combination of the key columns, not each key column individually:
Create table Wedstrijd
(
datum date not null,
aantal_geel int not null,
aantal_rood int not null,
Primary key (datum),
Foreign key (aantal_geel,aantal_rood)
REFERENCES kaart(aantal_geel,aantal_rood)
);

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)

Exporting foreign key from many to many relationship to another table sql

I've a table
CREATE TABLE [dbo].[CoursesOfferedToBatches] (
[CourseId] VARCHAR (50) NOT NULL,
[Batch] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC),
CONSTRAINT [FK_OfferedCourses_ToCourses] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Courses] ([Id]),
CONSTRAINT [FK_CoursesOfferedToBatches_ToBatches] FOREIGN KEY ([Batch]) REFERENCES [dbo].[Batches] ([Id])
);
When I export CourseId as foreign key from above table into below table as shown below, it gives error shown below after table
CREATE TABLE [dbo].[StudentsRegisterToCoursesOffered]
(
[StudentId] UNIQUEIDENTIFIER NOT NULL ,
[CourseId] VARCHAR(50) NOT NULL,
PRIMARY KEY ([CourseId], [StudentId]),
CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [Students]([StudentId]),
CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToCoursesOffered] FOREIGN KEY ([CourseId]) REFERENCES [CoursesOfferedToBatches]([CourseId])
)
Error:
Update cannot proceed due to validation errors. Please correct the
following errors and try again.
SQL71516 :: The referenced table '[dbo].[CoursesOfferedToBatches]'
contains no primary or candidate keys that match the referencing
column list in the foreign key. If the referenced column is a computed
column, it should be persisted.
My question finishes here but for reference I'm adding all relevant tables:
CREATE TABLE [dbo].[Courses] (
[Id] VARCHAR (50) NOT NULL,
[Name] VARCHAR (100) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Students] (
[StudentId] UNIQUEIDENTIFIER NOT NULL,
[DepartmentName] VARCHAR (50) NOT NULL,
[Address] VARCHAR (250) NULL,
[TwitterLink] VARCHAR (100) NULL,
[FacebookLink] VARCHAR (100) NULL,
[MemberSince] DATETIME NULL,
[ProfileViews] BIGINT DEFAULT ((0)) NULL,
[CNIC] CHAR (15) NULL,
[AboutMe] VARCHAR (3000) NULL,
PRIMARY KEY CLUSTERED ([StudentId] ASC),
CONSTRAINT [FK_Students_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Users] ([UserId]),
CONSTRAINT [FK_Students_ToDepartments] FOREIGN KEY ([DepartmentName]) REFERENCES [dbo].[Departments] ([Name])
);
CREATE TABLE [dbo].[Batches] (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The table CoursesOfferedToBatches needs to have its own primary key, which you have created as a compound key PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC). It is this compound key that would be a foreign key in StudentsRegisterToCoursesOffered and not just the CourseId.

MySQL error: Cannot add foreign key constraint?

There always be the error:"Cannot add foreign key constraint" when I create my last table.
System: Mac OS X 10.9
DB : MySQL 5.6.14
DBM : Sequel Pro
CREATE TABLE users (
uid INT AUTO_INCREMENT PRIMARY KEY,
uname VARCHAR(20) NOT NULL,
uemail VARCHAR(20) NOT NULL,
ucity VARCHAR(20),
upassw VARCHAR(20) NOT NULL
);
CREATE TABLE songs(
sid INT AUTO_INCREMENT PRIMARY KEY,
sname VARCHAR(20) NOT NULL,
srldate DATE NOT NULL
);
CREATE TABLE albums (
albid INT AUTO_INCREMENT PRIMARY KEY,
albname VARCHAR(20) NOT NULL,
albrldate DATE NOT NULL,
albrltime TIME NOT NULL
);
CREATE TABLE artists (
aid INT AUTO_INCREMENT PRIMARY KEY,
aname VARCHAR(20) NOT NULL
);
CREATE TABLE genres (
gid INT AUTO_INCREMENT PRIMARY KEY,
gname VARCHAR(20) NOT NULL
);
CREATE TABLE playlists (
uid INT NOT NULL,
sid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, sid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(sid) REFERENCES songs(sid)
);
CREATE TABLE u_like_a (
aid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(aid, uid),
FOREIGN KEY(aid) REFERENCES artists(aid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE be_fan (
aid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(aid, uid),
FOREIGN KEY(aid) REFERENCES artists(aid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE follow (
uid INT NOT NULL,
to_uid INT NOT NULL,
PRIMARY KEY(uid, to_uid),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(to_uid) REFERENCES users(uid)
);
CREATE TABLE u_like_g (
gid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(gid, uid),
FOREIGN KEY(gid) REFERENCES genres(gid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE u_share_pl(
uid INT NOT NULL,
from_uid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, from_uid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(from_uid) REFERENCES users(uid),
FOREIGN KEY(plname) REFERENCES playlists(plname),
FOREIGN KEY(plmdate) REFERENCES playlists(plmdate),
FOREIGN KEY(plmtime) REFERENCES playlists(plmtime)
); #####---> This is the last table.
ERROR comes from here. I really don't why.
I have check the type for all attributes. The type and name of attributes have no problem.
But the mysql always say "Cannot add foreign key constraint"
Here is you reference wrong forgien REFERENCES users(from_uid) in last table.
FOREIGN KEY(from_uid) REFERENCES users(from_uid)
from_uid not belong to users
This should be
FOREIGN KEY(from_uid) REFERENCES users(uid)
your playLists table has primary key combination of four columns, so you should supply all these four columns as forieng key in u_share_pl table.
Another composite key as a reference should be a single constraint like
FOREIGN KEY(from_uid,sid,plname,plmdate,plmtime) REFERENCES playlists(uid,sid,plname,plmdate,plmtime)
Your last table Create should be:
CREATE TABLE u_share_pl(
uid INT NOT NULL,
from_uid INT NOT NULL,
sid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, from_uid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(from_uid,sid,plname,plmdate,plmtime) REFERENCES playlists(uid,sid,plname,plmdate,plmtime)
);

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.