Use Composite Primary Key as Foreign Key - mysql

How can I use a composite primary key as a foreign key? It looks like my attempt does not work.
create table student
(
student_id varchar (25) not null ,
student_name varchar (50) not null ,
student_pone int ,
student_CNIC varchar (50),
students_Email varchar (50),
srudents_address varchar(250),
dept_id varchar(6),
batch_id varchar(4),
FOREIGN KEY (dept_id) REFERENCES department(dept_id),
FOREIGN KEY (batch_id) REFERENCES batch(batch_id),
CONSTRAINT pk_studentID PRIMARY KEY (batch_id,dept_id,student_id) )
create table files
(
files_name varchar(50) not null ,
files_path varchar(50),
files_data varchar(max),
files_bookmarks xml ,
FOREIGN KEY (pk_studentID ) REFERENCES student(pk_studentID ),
CONSTRAINT pk_filesName PRIMARY KEY (files_name) )

The line:
FOREIGN KEY (pk_studentID ) REFERENCES student(pk_studentID ),
is wrong. You can't use pk_studentID like that, this is just the name of the PK constraint in the parent table. To use a compound Primary Key as Foreign Key, you'll have to add the same number of columns (that compose the PK) with same datatypes to the child table and then use the combination of these columns in the FOREIGN KEY definition:
CREATE TABLE files
(
files_name varchar(50) NOT NULL,
batch_id varchar(4) NOT NULL, --- added, these 3 should not
dept_id varchar(6) NOT NULL, --- necessarily be NOT NULL
student_id varchar (25) NOT NULL, ---
files_path varchar(50),
files_data varchar(max), --- varchar(max) ??
files_bookmarks xml, --- xml ??
--- your question is tagged MySQL,
--- and not SQL-Server
CONSTRAINT pk_filesName
PRIMARY KEY (files_name),
CONSTRAINT fk_student_files --- constraint name (optional)
FOREIGN KEY (batch_id, dept_id, student_id)
REFERENCES student (batch_id, dept_id, student_id)
) ENGINE = InnoDB ;

Related

i am trying to create foreign keys but i got error 1822 .. please see my code below

CREATE TABLE employee(
empid int auto_increment primary key,
empfirstname varchar(200) not null,
emplastname varchar(200) not null,
email varchar(200) not null,
officenumber int not null
);
CREATE TABLE customer(
custid int auto_increment primary key,
firstname varchar(200) not null,
lastname varchar(200) not null,
address varchar(200) not null,
contact varchar(200)
);
CREATE TABLE product(
productid int auto_increment primary key,
productdesc varchar(500) not null,
weight int not null,
unit_cost int not null
);
CREATE TABLE productorder(
productid int,
orderid int,
primary key(productid,orderid),
constraint fk3 foreign key (productid) references product(productid),
constraint fk4 foreign key (orderid) references productorder(orderid)
);
CREATE TABLE salesorder(
salesorderid int auto_increment primary key,
empid int not null,
custid int not null,
orderdate date not null,
shippingmethod varchar (200) not null,
constraint a_fk1 foreign key (empid) references employee(empid),
constraint a_fk2 foreign key (custid) references customer(custid)
);
What is this meant to do?:
constraint fk4 foreign key (orderid) references productorder(orderid)
It's not uncommon for a table to have a foreign key back to its own primary key, such as for records which have a parent/child relationship. But that doesn't seem to be the case here.
More to the point of the error though, this isn't referencing the entire primary key for the target table. That key has two fields:
primary key(productid,orderid)
So the DBMS can't create the foreign key because its structure doesn't match the target primary key.
If you want to create that foreign key, it would need to match. Probably something like this:
constraint fk4 foreign key (productid,orderid) references productorder(productid,orderid)
But it doesn't appear that you need that foreign key at all, because it doesn't seem to make sense in your data model. Instead I suspect orderid might need to be autoincrement and just use the productid foreign key. Something like this:
CREATE TABLE productorder(
orderid int auto_increment primary key,
productid int,
constraint fk3 foreign key (productid) references product(productid)
);
(Note that there could be more changes you'd want to make to your data model. This answer doesn't purport to provide you with a complete production-ready data model, just to correct the error. Your data model is likely to change/evolve as you develop your system.)
Its normal,
The foreign key in table **productorder**
is refereing to the table itself:
constraint fk4 foreign key (orderid) references **productorder**(orderid)
In order to achieve the self-referencing constraint on the table productorder, you need to add another column with the same type and make typical referencing.
For instance :
Create table productorder (
productid int,
orderid int,
orderid_parent int,
primary key(productid,orderid),
constraint fk_self foreign key(orderid) references productorder(orderid_parent)
)

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.

can someone explain why im getting this error with sql query

create table Department (
Dep_ID int not null,
Dep_Name varchar(30),
primary key (Dep_ID),
)
create table Course (
C_ID int not null,
C_Name varchar (30) not null,
C_Duration varchar (10) not null,
DegreeType varchar (20),
Dep_ID int,
primary key (C_ID),
constraint DEP_ID1 foreign key (Dep_ID) references Department (Dep_ID) on update cascade,
)
create table Student (
St_ID int not null,
St_Name varchar (100),
St_age smallint,
St_gender Varchar(6),
St_tel int,
St_ADD varchar (100) not null,
St_city varchar (50)not null,
St_type varchar (20) not null,
St_nationality varchar (5) not null,
Dep_ID int,
C_ID int,
primary key (St_ID),
constraint DEP_ID foreign key (Dep_ID) references Department(Dep_ID) on update cascade,
constraint CO_ID foreign key (C_ID) references Course(C_ID) on update cascade,
)
create table Staff (
Sta_ID int not null,
Sta_Name varchar (100) not null,
Sta_type varchar (20) not null,
Sta_Add varchar (100) not null,
Sta_tel int ,
Dep_ID int,
primary key (Sta_ID),
constraint DEeP_ID foreign key (Dep_ID) references Department (Dep_ID) on update cascade,
)
this is the error im getting why cant i use cascade update on
composite keys
Msg 1785, Level 16, State 0, Line 19
Introducing FOREIGN KEY constraint 'CO_ID' on table 'Student' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 0, Line 19
Could not create constraint. See previous errors.
I had done a research and get to know that this problem can be resolve by changing the line :
constraint CO_ID foreign key (C_ID) references Course(C_ID) on update cascade, to constraint CO_ID foreign key (C_ID) references Course(C_ID) on update No Action,
I have get a explanation on the following link :
Foreign key constraint may cause cycles or multiple cascade paths?
This may resolve your problem.
Your problem is in table 'Exam'. Since you specified no source for this table I can only guess ;-)
Exam contains a foreign key constraint Course_ID2
It seems that this foreign key also refrences to Department or Course.
So have a look into this constraint first. If you need further assistance, please post source of table definition Exam, Department and Course
When you are adding foreign key
They need to be exactly the same data type in both tables.
Try with your query it works fine with me i just remove "," from end of your column
CREATE TABLE Department (
Dep_ID INT NOT NULL,
Dep_Name VARCHAR(30),
PRIMARY KEY (Dep_ID)
)
CREATE TABLE Course (
C_ID INT NOT NULL,
C_Name VARCHAR (30) NOT NULL,
C_Duration VARCHAR (10) NOT NULL,
DegreeType VARCHAR (20),
Dep_ID INT,
PRIMARY KEY (C_ID),
CONSTRAINT DEP_ID1 FOREIGN KEY (Dep_ID) REFERENCES Department (Dep_ID) ON UPDATE CASCADE
)
CREATE TABLE Student (
St_ID INT NOT NULL,
St_Name VARCHAR (100),
St_age SMALLINT,
St_gender VARCHAR(6),
St_tel INT,
St_ADD VARCHAR (100) NOT NULL,
St_city VARCHAR (50)NOT NULL,
St_type VARCHAR (20) NOT NULL,
St_nationality VARCHAR (5) NOT NULL,
Dep_ID INT,
C_ID INT,
PRIMARY KEY (St_ID),
CONSTRAINT DEP_ID FOREIGN KEY (Dep_ID) REFERENCES Department(Dep_ID) ON UPDATE CASCADE,
CONSTRAINT CO_ID FOREIGN KEY (C_ID) REFERENCES Course(C_ID) ON UPDATE CASCADE
)
CREATE TABLE Staff (
Sta_ID INT NOT NULL,
Sta_Name VARCHAR (100) NOT NULL,
Sta_type VARCHAR (20) NOT NULL,
Sta_Add VARCHAR (100) NOT NULL,
Sta_tel INT ,
Dep_ID INT,
PRIMARY KEY (Sta_ID),
CONSTRAINT DEeP_ID FOREIGN KEY (Dep_ID) REFERENCES Department (Dep_ID) ON UPDATE CASCADE
)

Foreign Key Unexpected

I'm using MySQL workbench and I am trying to create a table consist of foreign key using SQL Query. I am having problem with the Foreign part.
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int foreign key references employee_profile(eID)
)
Your syntax is wrong. Try:
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (keyname) references employee_profile(eID)
)
For more information see the mysql documentation
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (eID) references employee_profile(eID)
)
SQLFiddle demo
Check FOREIGN KEYS in MySQL.
Try this:
CREATE TABLE employee_position
(
ePID INT NOT NULL AUTO_INCREMENT,
ePName VARCHAR(45) NOT NULL,
eID INT NOT NULL,
PRIMARY KEY (ePID),
KEY CustomerID (eID),
CONSTRAINT FK_employee_position_EP
FOREIGN KEY (eID)
REFERENCES employee_profile (eID) ON DELETE CASCADE ON UPDATE CASCADE
);

How do I create a table with a two primary keys of two foreign keys?

create table Machine
(
Machine_ID int primary key,
Machine_Name varchar(30)
Machine_Title varchar(30)
)
create table Part
(
Part_ID int primary key,
Part_Name varchar(30),
Part_Description varchar(30)
)
//How do I make this table below?
create table Machine-Part
(
Machine_ID int foreign key references (Machine.Machine_ID),
Part_ID int foreign key references (Part.Part_ID)
Factory_Note varchar(30);
)
Mysql complains there is a problem with syntax?
Desired Result: have Table 'Machine-Part' use 'Machine_ID' & 'Part_ID' as both primary keys (which are both foreign keys).
If you declare the constraint separately (table level), it makes more sense
create table Machine-Part
(
Machine_ID int NOT NULL ,
Part_ID int NOT NULL ,
Factory_Note varchar(30) NULL,
PRIMARY KEY (Machine_ID, Part_ID),
UNIQUE INDEX (Part_ID, Machine_ID),
foreign key (Machine_ID) references (Machine.Machine_ID),
foreign key (Part_ID) references (Part.Part_ID)
)
Link tables almost always need a reverse index too
Something like this -
CREATE TABLE Machine(
Machine_ID INT PRIMARY KEY,
Machine_Name VARCHAR(30),
Machine_Title VARCHAR(30)
)
ENGINE = INNODB;
CREATE TABLE Part(
Part_ID INT PRIMARY KEY,
Part_Name VARCHAR(30),
Part_Description VARCHAR(30)
)
ENGINE = INNODB;
create table `Machine-Part`(
Machine_ID int,
Part_ID int,
Factory_Note varchar(30),
CONSTRAINT fk_Machine_ID FOREIGN KEY (Machine_ID) REFERENCES Machine(Machine_ID),
CONSTRAINT fk_Part_ID FOREIGN KEY (Part_ID) REFERENCES Part(Part_ID)
)
ENGINE = INNODB;
You can find all information on these pages:
FOREIGN KEY Constraints
CREATE TABLE Syntax