The current tables I have are as follows:
CREATE TABLE course(
CourseNum INT(11),
CourseName VARCHAR(30),
NumOfUnit INT(11),
PRIMARY KEY(CourseNum)
);
CREATE TABLE timeandloc(
CourseNum INT(11),
Quarter VARCHAR(20),
DayTime VARCHAR(40),
RoomNum INT,
PRIMARY KEY(CourseNum, Quarter, DayTime),
FOREIGN KEY(CourseNum) REFERENCES course (CourseNum)
);
I was able to add those fine using a query, but when I try to add this table:
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
I get
Error code: 1215. Cannot add foreign key constraint.
It seems to be this line that's the culprit:
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
When I try to add the table without that line, everything works fine without a hitch.
I'm very new to MySQL and databases in general so I'm not sure what's wrong. Any help would be great. Thanks.
create a separate index on Quarter field in timeandloc table and then create problematic create table query.
alter table timeandloc add index idx_Quarter(Quarter);
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
Update:
For performance point of view joining field in both tables (parent/child) should be indexed. When we create foreign key then mysql itself create an index on the field we create foreign key but could not allow without index on referenced column in referenced table. As index works from left to right, so in your case index for Quarter column will not be used from primary key, so need to create a separate index on it.
Related
This question already has an answer here:
ERRO 1215. MySql InnoDB
(1 answer)
Closed 2 years ago.
Hey so i just started using mysql and made a small database, but then i tried to alter some tables to impliment some foreign keys and I got the error: ERROR 1005 (HY000): Can't create table etron3.purchase (errno: 150 "Foreign key constraint is incorrectly formed").
I know its cause when altering TillNo into a foreing key of TillN, but i cant really see what the problem is.
create table BRANCH(BranchNo INT, BranchAddr VARCHAR(25), BranchTell INT, PRIMARY KEY(BranchNo));
/*Create table CUSTOMER*/
create table CUSTOMER(CustNum INT, CustTell INT, CustFname VARCHAR(15), CustLname VARCHAR(15), CustCountry VARCHAR(20),
CustTown VARCHAR(20), CustStreet VARCHAR(20), CustPostCode CHAR(7), CustDob DATE, CustEmail VARCHAR(45), PRIMARY KEY(CustNum, CustTell));
/*Create table ASSISTANT*/
create table ASSISTANT(SalesPNo INT,TillN INT , SalePFname VARCHAR(20), SalePLname VARCHAR(20), PRIMARY KEY(SalesPNo, TillN));
/*Create table PURCHASE*/
create table PURCHASE(TDateTime DATETIME, TillNo INT, CustNo INT, AssistantNo INT, ProdCode INT, Qty INT, PRIMARY KEY(TDateTime));
/*Create table SUPPLIER*/
create table SUPPLIER(SupCnum INT, SupCname VARCHAR(15), SupFname VARCHAR(15), SupLname VARCHAR(15), SupEmail VARCHAR(30), ProdNum INT, PRIMARY KEY(SupCnum));
/*Create table PRODUCT*/
create table PRODUCT(ProductCode INT, PType VARCHAR(20), Price INT, OfferPrice INT, PRIMARY KEY(ProductCode, PType));
/*Create table PRODTYPE*/
create table PRODTYPE(ProdGroup VARCHAR(20), PCode INT, PRIMARY KEY(ProdGroup));
/*Altering tables, adding foreign keys, so that I don't get any errors*/
/*Add primary and foreign keys to PURCHASE*/
ALTER TABLE PURCHASE
ADD FOREIGN KEY(AssistantNo) REFERENCES ASSISTANT(SalesPNo);
ALTER TABLE PURCHASE
ADD FOREIGN KEY(ProdCode) REFERENCES PRODUCT(ProductCode);
ALTER TABLE PURCHASE
ADD FOREIGN KEY(CustNo) REFERENCES CUSTOMER(CustNum);
ALTER TABLE PURCHASE
ADD FOREIGN KEY (TillNo) REFERENCES ASSISTANT(TillN);
/*Add foreign key to SUPPLIER*/
ALTER TABLE SUPPLIER
ADD FOREIGN KEY(ProdNum) REFERENCES PRODUCT (ProductCode);
/*Add primary and foreign keys to PRODTYPE*/
ALTER TABLE PRODTYPE
ADD FOREIGN KEY(PCode) REFERENCES PRODUCT(ProductCode);
Consider this part of your code:
ALTER TABLE PURCHASE
ADD FOREIGN KEY(AssistantNo) REFERENCES ASSISTANT(SalesPNo);
ALTER TABLE PURCHASE
ADD FOREIGN KEY (TillNo) REFERENCES ASSISTANT(TillN);
The primary key of the ASSISTANT table is (SalesPNo, TillN).
Technically, you cannot have a foreign key point at the second column only of the other table's primary key - MySQL wants the referred column to be indexed, or to appear first in a compound index.
Functionnaly, you most probably want a compound foreign key rather than two individual foreign keys, so:
ALTER TABLE PURCHASE
ADD FOREIGN KEY (AssistantNo, TillNo) REFERENCES ASSISTANT(SalesPNo, TillN);
With this change, your script runs succesfully in this db fiddle.
Recommended reading: MySQL Foreign Keys - Constraints and Restrictions.
I'm trying to create a table named appointment, though when I try to create it I receive the error:
Cannot add foreign key constraint
My SQL code is as follows:
CREATE TABLE APPOINTMENT(
APNo VARCHAR(5),
PNo VARCHAR(5),
DNo VARCHAR(5),
APDATE DATETIME
);
ALTER TABLE APPOINTMENT
ADD PRIMARY KEY (APNo),
ADD FOREIGN KEY (PNo) REFERENCES PATIENT(PNo),
ADD FOREIGN KEY (DNo) REFERENCES DOCTOR(DNo)
;
You syntax looks ok. You are not showing the DDL for referrenced tables PATIENT and DOCTOR, however it is likely that the error happens because one of MySQL foreign keys requirements is not met.
Quotes from the documentation:
Corresponding columns in the foreign key and the referenced key must have similar data types.
You must ensure that both DOCTOR(DNo) and PATIENT(PNo) are VARCHAR(5).
MySQL requires indexes on foreign keys and referenced keys. [...] Such an index is created on the referencing table automatically if it does not exist.
Ideally, DOCTOR(DNo) and PATIENT(PNo) should be the primary key of their respective tables. Else, an index must exist for each of them (it could be a multi-column index where the referrenced column appears once).
See this db fiddle for a working example:
CREATE TABLE PATIENT(PNo VARCHAR(5) PRIMARY KEY);
CREATE TABLE DOCTOR(DNo VARCHAR(5) PRIMARY KEY);
CREATE TABLE APPOINTMENT(
APNo VARCHAR(5),
PNo VARCHAR(5),
DNo VARCHAR(5),
APDATE DATETIME
);
ALTER TABLE APPOINTMENT
ADD PRIMARY KEY (APNo),
ADD FOREIGN KEY (PNo) REFERENCES PATIENT(PNo),
ADD FOREIGN KEY (DNo) REFERENCES DOCTOR(DNo)
;
I am trying to create a database containing information from a game for an assignment but am having issues when creating the tables with assigning the primary and foreign keys. Any help would be amazing.
The error code I am getting is: #1215 - Cannot add foreign key constraint on table Boss. It creates the first table fine it just stops working and throws the error at the foreign key when creating table boss.
Within the item table the field Boss needs to be able have the same data entered for multiple different items.
CREATE TABLE item ( ID SERIAL, Name VARCHAR(35), Boss VARCHAR(25), Type VARCHAR(20), Slot VARCHAR(20), PRIMARY KEY (Name,Boss) );
CREATE TABLE boss ( ID SERIAL, Boss VARCHAR(25), Type VARCHAR(20), Location VARCHAR(20), Difficulty INT, PRIMARY KEY (ID, Location), FOREIGN KEY (Boss) REFERENCES item(Boss) );
CREATE TABLE dungeon ( ID SERIAL, Name VARCHAR(25), Location VARCHAR(20), Rating INT, PRIMARY KEY (Name), FOREIGN KEY (Location) REFERENCES boss(Location) );
I can see many things wrong with your db creation script, but I will only stick to the ones that immediately affect getting it to work in the first place:
You should always refer to another table through its primary key and nothing else.
Your references are put in the wrong tables. If you want to refer to a "boss" from "item" then you should do just that and not refer to "item" from "boss".
But the most important thing is that references should be of the same type as the primary keys they refer to.
A composite key is a bad idea when you don't really need one.
So, a working script would be:
CREATE TABLE dungeon ( ID BIGINT(20), Name VARCHAR(25), Location VARCHAR(20), Rating INT, PRIMARY KEY (ID) );
CREATE TABLE boss ( ID BIGINT(20), Type VARCHAR(20), LocationId BIGINT(20), Difficulty INT, PRIMARY KEY (ID), FOREIGN KEY (LocationId) REFERENCES dungeon (ID) );
CREATE TABLE item ( ID BIGINT(20), Name VARCHAR(35), BossId BIGINT(20), Type VARCHAR(20), Slot VARCHAR(20), PRIMARY KEY (ID), FOREIGN KEY (BossId) REFERENCES boss (ID) );
You can adjust it to your needs, but before doing that, I would suggest reading a good book on database design or -at least- a tutorial on basic relational databases principles.
I am confused as to why error 1215: cannot add foreign key constraint is occurring in my code. Does anybody have any ideas?
The first four tables create themselves fine, but the error is thrown when I try to create the Stars table. I am not sure what's going wrong, as the keys being referenced are primary keys and so they must be unique and non-null. Plus, those keys exist as the previous tables have been created first. It might just be a stupid mistake I made, but its better to have fresh eyes look at it, right?
This database is simplistic as it is because I'm doing it for a school assignment.
create table MovieExec
(
execName varchar(40),
certNum numeric(30, 0),
address varchar(50),
networth real,
primary key(execName),
unique key(certNum)
);
create table Stud
(
studName varchar(30),
address varchar(50),
presCNum numeric(30, 0),
primary key(studName),
foreign key (presCNum) references MovieExec(certNum)
);
create table MovieStar(
starName varchar(30),
address varchar(50),
gender varchar(1),
birthdate date,
primary key(starName)
);
create table Movies
(
movieTitle varchar(30),
movieYear numeric(4,0),
length numeric(3,0),
genre varchar(30),
studioName varchar(30),
producerCNum numeric(30, 0),
primary key (movieTitle, movieYear),
foreign key (producerCNum) references MovieExec(certNum),
foreign key (studioName) references Stud(studName)
);
create table Stars
(
movieTitle varchar(30),
movieYear numeric(4,0),
starName varchar(30),
primary key (movieTitle, movieYear, starName),
foreign key (movieTitle) references Movies(movieTitle),
foreign key (movieYear) references Movies(movieYear),
foreign key (starName) references MovieStar(starName)
);
It should be a composite foreign key for the title and the year:
foreign key (movieTitle, movieYear) references Movies(movieTitle, movieYear),
foreign key (starName) references MovieStar(starName)
It should be composite because that's the exact PK of Movies table and that's the only UNIQUE combination there currently available.
Then as #CBroe mentioned in their answer it would be a good idea to index the Stars.starName column.
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html:
“[…] in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order”
In your Movies table, you only have a primary key on the combination (movieTitle, movieYear) – but movieYear is not the first column in that key, and therefor
foreign key (movieYear) references Movies(movieYear)
in your CREATE statement for the stars table fails.
Add a key on Movies.movieYear – then creating a foreign key referencing that column on the stars table will work.
FYI: MySQL has a YEAR data type – you should use that, instead of a NUMERIC for your movie year.
And you are mixing singular and plural in your table names. Convention is to use the singular of the object that a table holds as table name; but at least you should try and be consistent with your naming scheme.
I am new to databases and I keep getting an error when I try to create these tables. Where is a mistake?
I have found loads of questions similar to mine, but they didn't help me to resolve this problem.
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);
This is from INNODB STATUS.
LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
FOREIGN KEY (course_name) REFERENCES course (course_name)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Your primary key is set to cou_id and course_name in your course table. To add a foreign key constraint in your students_marks table, you'd have to reference both fields (and include both fields in your table definition):
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
cou_id VARCHAR(3),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);
SQL Fiddle Demo
You are referencing only one field of a composed primary key!