SQL Foriegn Key
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
A Foreign Key is a primary key in Another table, which is to be referred in current table.
This helps us in separating tables and maintain relationships between them.
Example: We can have a department table and maintain a foreign key in employee table to link him to the department.
Example: Consider the following Employee table:
Employee Table
FIRSTNAME
LASTNAME
AGE
DEPARTMENTID
Rambo
Robert
25
1
Mugambo
Satraj
37
1
Nagashekar
Rao
47
2
Tom
Harry
27
2
Dana
Laura
21
4
Rambo
Fox
57
4
Giselle
Chivvi
87
3
Department Table
DEPARTMENTID
DEPARTMENTNAME
1
Engineering
2
Management
3
Finance
4
Kitchen
The DEPARTMENTID column in Employee table is a foreign key.
The DEPARTMENTID column in Department table is a primary key.
A foriegn key can be created at the time of creating a table.
CREATE TABLE EMPLOYEE(
EMPID INT NOT NULL,
EMPNAME VARCHAR(50) NOT NULL,
EMPDESIGNATION VARCHAR(50),
PRIMARY KEY(EMPID),
FOREIGN KEY(DEPARTMENTID) REFERENCES DEPARTMENT(DEPARTMENTID);
);
Alternatively, a foreign key can be created at a later time, using ALTER command.
ALTER TABLE EMPLOYEE
ADD CONSTRAINT FKDEPARTMENT
FOREIGN KEY (DEPARTMENTID) REFERENCES DEPARTMENT(DEPARTMENTID);