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)
;
Related
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),
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.
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.
I'm very new to SQL, I'm trying to define a 2 tables Hospital and Hospital_Address but when I'm trying to add foreign key in Hospital_Address it throws an error: "1215: Cannot add foreign key"
create table Hospital (
HId Int not null,
HName varchar(40) not null,
HDept int, Hbed Int,
HAreaCd int not null,
Primary Key (HId)
);
create table Hospital_Address (
HAreaCd Int not null,
HArea varchar(40) not null,
HCity varchar(40),
HAdd1 varchar(40),
HAdd2 varchar(40),
Primary Key (HArea),
foreign key (HAreaCd) references Hospital (HAreaCd));
Please help me in this regard. Thanks in advance.
MySQL requires that there be an index on the HAreaCd column in the parent Hospital table, in order for you to reference that column in a FOREIGN KEY constraint.
The normative pattern is for the FOREIGN KEY to reference the PRIMARY KEY of the parent table, although MySQL extends that to allow a FOREIGN KEY to reference a column that is a UNIQUE KEY, and InnoDB extends that (beyond the SQL standard) and allows a FOREIGN KEY to reference any set of columns, as long as there is an index with those columns as the leading columns (in the same order specified in the foreign key constraint.) (That is, in InnoDB, the referenced columns do not need to be unique, though the behavior with this type of relationship may not be what you intend.)
If you create an index on that column in Hospital table, e.g.:
CREATE INDEX Hospital_IX1 ON Hospital (HAreaCd);
Then you can create a foreign key constraint that references that column.
However, because this is a non-standard extension of MySQL and InnoDB, the "best practice" (as other answers here indicate) is for a FOREIGN KEY to reference the PRIMARY KEY of the foreign table. And ideally, this will be a single column.
Given the existing definition of the Hospital table, a better option for a foreign key referencing it would be to add the Hid column to the Hospital_Address table
... ADD HId Int COMMENT 'FK ref Hospital.HId'
... ADD CONSTRAINT FK_Hospital_Address_Hospital
FOREIGN KEY (HId) REFERENCES Hospital (HId)
To establish the relationship between the rows, the values of the new HId column will need to be populated.
You cannot add a foreign key to a non-primary key element of another table usually.
If you really need to do so, refer to this question for help : Foreign Key to non-primary key
HAreaCd in the Hospital table should be a primary key. Only then can you reference it in the Hospital_Address table
I'm not sure what I'm doing wrong here, but I get an error:
Error Code: 1005. Can't create table 'erm.section' (emo:150)
Here is the code. The 'course' table is created successfully. I tried modifying the name of the course_number attritube in the 'section' table but that didn't work.
USE erm;
CREATE TABLE course
(
course_name VARCHAR(30) NOT NULL,
course_number VARCHAR(20) NOT NULL,
credit_hours INT NOT NULL,
department VARCHAR(10),
CONSTRAINT course_pk PRIMARY KEY (course_name)
);
CREATE TABLE section
(
section_identifier INT NOT NULL,
course_number VARCHAR(20),
semester VARCHAR(10) NOT NULL,
school_year VARCHAR(4) NOT NULL,
instructor VARCHAR(25),
CONSTRAINT section_pk PRIMARY KEY (section_identifier),
CONSTRAINT section_fk FOREIGN KEY (course_number)
REFERENCES course (course_number)
ON DELETE SET NULL
ON UPDATE CASCADE
);
course_number is not a primary key in the table course.
the foreign key in the table section must reference a primary key form another table.
You have to create an index on the column referenced by the foreign key:
alter table course add index (course_number);
(It doesn't have to be a primary key index.) From the MySQL documentation:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
AFAIK, dropping the CONSTRAINT, then rename, then add the CONSTRAINT back is the only way. Backup first!
to drop it use this
ALTER TABLE section
DROP FOREIGN KEY course_number
and to add it again use this
ALTER TABLE section
ADD FOREIGN KEY (course_number)
REFERENCES course (course_number)