MySQL Foreign Key constraint fails for multiple keys - mysql

Hi I am creating several tables some of which have multiple keys linking to the same table. When I try to create the foreign key links I am given:
errno: 150 "Foreign key constraint is incorrectly formed"
Here are the tables I am creating:
create table EventFeed (
EventFeedID integer auto_increment not null,
EventName varchar(100),
EventTime Timestamp,
EventLocation varchar(100),
primary key (EventFeedID)
);
create table Calendar (
MyEventID integer auto_increment not null,
EventFeedID integer,
EventName varchar(100),
EventTime Timestamp,
EventLocation varchar(100),
AttendeeID varchar(100),
primary key (MyEventID),
foreign key (EventFeedID) references EventFeed (EventFeedID),
foreign key (EventName) references EventFeed (EventName),
foreign key (EventTime) references EventFeed (EventTime),
foreign key (EventLocation) references EventFeed (EventLocation),
foreign key (AttendeeID) references Users (UserID)
);
The error seems to be coming from the foreign keys in the 'Calendar' table however some of my other tables have used similar foreign keys and given no errors
can anyone advise what I am doing wrong?
Any help is much appreciated

You cannot have a foreign key on the column which is a non-primary key except the columns with unique constraint. So you have to make EventName, EventTime, etc unique if you want it to be referred by a foreign key.
You can check here at: Technet Microsoft
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
You can see this fiddle for working example: http://sqlfiddle.com/#!9/05663

Related

Error Code: 1824. Failed to open the referenced table even though it is already created

I am building a database for a school project, but for some reason I cannon make a foreign key reference between 2 tables (only those 2). My project has 14 tables and it works fine for all the others.
The tables are made like:
create table degree(
title varchar(50),
idryma varchar(40),
bathmida enum('High School', 'Univercity', 'Master', 'PHD'),
constraint degree_id primary key (title, idryma)
);
create table has_degree(
degree_title varchar(50),
degree_idryma varchar(40),
employee_username varchar(12),
acquisition_year year(4),
grade float(3,1),
constraint has_degree_id primary key (degree_title, degree_idryma, employee_username)
);
And then I try to alter the table so that I make the foreign key connections:
alter table has_degree add foreign key (degree_title) references degree(title);
alter table has_degree add foreign key (degree_idryma) references degree(idryma);
But I keep on getting
Error Code: 1824. Failed to open the referenced table 'degree'
I have tried to make them like that:
create table degree(
title varchar(50),
idryma varchar(40),
bathmida enum('High School', 'Univercity', 'Master', 'PHD'),
constraint degree_id primary key (title, idryma)
);
create table has_degree(
degree_title varchar(50),
degree_idryma varchar(40),
employee_username varchar(12),
acquisition_year year(4),
grade float(3,1),
foreign key (degree_title) references degree(title),
foreign key (degree_idryma) references degree(idryma),
/*employee is an other table that I use and that works just fine*/
foreign key (employee_username) references employee(employee_username),
constraint has_degree_id primary key (degree_title, degree_idryma, employee_username)
);
But the only thing that changes is that I get
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'has_degree_ibfk_2' in the referenced table 'degree'
The columns in your foreign key in table has_degree must be the same as the columns in the primary key of the referenced table degree.
In this case, the primary key of degree consists of two varchar columns.
So the foreign key in has_degree that references it must also be only two varchar columns, and values in those columns in has_degree must match exactly the values in a row of degree.
You defined the foreign key this way:
foreign key (degree_title) references degree(title),
foreign key (degree_idryma) references degree(idryma),
But that's two foreign keys, each having a single column. You need one foreign key with two columns:
foreign key (degree_title, degree_idryma) references degree(title, idryma),

error 1215: CANNOT ADD FOREIGN KEY CONSTRAINT ; Composite Foreign key

I am getting ERROR CODE 1215: cannot add foreign key constraint for the child table.
Parent table has composite primary key. I want to use that composite primary key as foreign key in the child table.
Please guide me.
PARENT TABLE
CREATE TABLE health.procedures(
Specialty varchar(40),
Procedure_Name varchar(60),
PRIMARY KEY (Procedure_Name, Specialty)
);
CHILD TABLE
CREATE TABLE health.procedureProvided(
specialization varchar(40),
procedure_name varchar(60),
Insurance_ID int REFERENCES health.insurance (idInsurance),
Hospital_ID int REFERENCES health.hospital (idHospital) ,
Doctor_ID int REFERENCES health.doctor( idDoctor) ,
CONSTRAINT procedures_fk foreign key (specialization,procedure_name)references health.procedures(Specialty,Procedure_Name) ,
PRIMARY KEY (specialization, procedure_name, Insurance_ID, Hospital_ID, Doctor_ID)
);
You are specifying a foreign key that is invalid. Your primary key is procedure_name in health.procedure, but you are trying to create a composite foreign key in health.procedureProvided. You can't create that as a foreign key as the column Specialty in the master table is not part of the primary. A foreign key must contain all the columns in the contributing table's primary key but cannot contain values that are not in that primary key. You have three real options. 1. Specify Specialty as being a component of the primary key in procedure. Unfortunately that means the procedure will not necessarily by unique, it will be unique by specialty. 2. add a surrogate key - a system generated sequence value, uuid or something else (timestamps are not recommended). 3. Create validation tables valid_procedures and valid_specialties and use the table health.procedure as an intersection between those to provide valid procedures and correlated specialties and then you could migrate the entire primary key.

SQL Syntax error phpmyadmin #1064

i have been trying to figure out what is wrong but could not find the problem.
MySQL said: Documentation
1064
CREATE TABLE Show
(
Show_Id int NOT NULL AUTO_INCREMENT,
FOREIGN KEY (cinema_id) REFERENCES cinema(cinema_id),
FOREIGN KEY (movie_id) REFERENCES movie(movie_id),
FOREIGN KEY (show_time_id) REFERENCES show_time(show_time_id),
FOREIGN KEY (show_day_id) REFERENCES show_day(show_day_id),
PRIMARY KEY (show_id)
);
The foreign key constraint is applied to an already declared column. It doesn't do the declaration. So, you need to declare the columns:
CREATE TABLE Shows (
Show_Id int NOT NULL AUTO_INCREMENT,
Cinema_id int,
Movie_id int,
Show_Time_id int,
Show_Day_id int,
FOREIGN KEY (cinema_id) REFERENCES cinema(cinema_id),
FOREIGN KEY (movie_id) REFERENCES movie(movie_id),
FOREIGN KEY (show_time_id) REFERENCES show_time(show_time_id),
FOREIGN KEY (show_day_id) REFERENCES show_day(show_day_id),
PRIMARY KEY (show_id)
);
Note that show is a reserved word in MySQL, so I changed the table name to shows. I typically use plurals for table names anyway, because they are collections of things.

MySQL error 1005 errno 150 Foreign key constraint is incorrectly formed

I have created the following tables:
Stops:
CREATE TABLE Stop (
routeNo DECIMAL (4,0) UNSIGNED,
stopNo DECIMAL(3,0) UNSIGNED,
latitude DECIMAL(19,16),
longitude DECIMAL(19,16),
CONSTRAINT PK_Location PRIMARY KEY (routeNo, stopNo),
CONSTRAINT FK_stop_location FOREIGN KEY (latitude,longitude) REFERENCES Location(latitude,longitude),
CONSTRAINT FK_stop_route FOREIGN KEY (routeNo) REFERENCES Route(routeNo)
);
And the table WorkDay:
CREATE TABLE Workday (
theDate DATE PRIMARY KEY,
notes VARCHAR(30)
);
I then try to create the table Order Delivery with the following code:
CREATE TABLE OrderDelivery
(
routeNo DECIMAL(4,0) UNSIGNED,
stopNO DECIMAL(3,0) UNSIGNED,
orderNo INT(9),
CONSTRAINT pk_Orders PRIMARY KEY (routeNo, stopNo, orderNo),
deliveryDateExpected DATE,
deliveryTime TIME,
customerName VARCHAR(40),
creditCardNo CHAR(16) NOT NULL,
customerRanking ENUM('platinum','gold','occasional','one-off'),
CONSTRAINT fk_Routes FOREIGN KEY (routeNo) REFERENCES Stop(routeNo),
CONSTRAINT fk_Stops FOREIGN KEY (stopNo) REFERENCES Stop(stopNo),
CONSTRAINT fk_Dates FOREIGN KEY (deliveryDateExpected) REFERENCES Workday(theDate)
);
However every time i try to create the OrderDelivery table it gives the error that the foreign key is incorrectly formed
"SQL Error (1005): Can't create table 'harry.OrderDelivery' (errno:150)Foreign key constraint is incorrectly formed"
How can i rectify this?
You can't create a foreign key to a table with a multiple primary key referencing only one field of that primary key.
So your problem lies here:
CONSTRAINT fk_Routes FOREIGN KEY (routeNo) REFERENCES Stop(routeNo),
CONSTRAINT fk_Stops FOREIGN KEY (stopNo) REFERENCES Stop(stopNo),
You should change it to
CONSTRAINT fk_Stops_Routes
FOREIGN KEY (routeNo, stopNo)
REFERENCES Stop(routeNo, stopNo),
Or depending on your requirements you have to change your model to fit your needs.

Cannot add foreign key constraint on a date field

I have the following SQL statements:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);
CREATE TABLE fake(
Name varchar(255),
PName varchar(255),
PGeburtsdatum date,
CONSTRAINT pk_fake PRIMARY KEY (Name,PName,PGeburtsdatum),
CONSTRAINT fk_PName2 FOREIGN KEY (PName) REFERENCES patient(Name) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_PGeburtsdatum FOREIGN KEY (PGeburtsdatum) REFERENCES patient(Geburtsdatum) ON DELETE CASCADE ON UPDATE CASCADE
);
This gives me the error "#1215 - Cannot add foreign key constraint". If I remove the last constraint in the second table creation everything works. All my other foreign key constraints work exactly the same way. What am I missing here?
Not sure why you tagged a mysql question as db2. Anyway, the MySQL documentation states:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan
So add an index in the Geburtsdatum column:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
INDEX (Geburtsdatum),
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);