Foreign Key
Foreign Key
MANAGEMENT
SYSTEM
Contents
Foreign Key
Index
Control Functions
CONSTRAINTS- FOREIGN KEY
• A FOREIGN KEY in MySQL creates a link between two tables by one specific
column of both tables. The specified column in one table must be a PRIMARY
KEY and referred by the column of another table known as FOREIGN KEY.
CREATE TABLE Persons (
ID int NOT NULL,
Name varchar(255) NOT NULL,
Age int,
PRIMARY KEY (ID)
);
CREATE TABLE Orders (
OrderID int NOT NULL,
Order_Date Date NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons
(ID));
mysql> select * from persons;
+----+-------+------+
| ID | Name | Age |
+----+-------+------+
| 1 | Ram | 21 |
| 2 | Riya | 22 |
| 3 | Priya | 23 |
+----+-------+------+
3 rows in set (0.00 sec)
• CASCADE: Delete or update the row from the parent table and automatically
delete or update the matching rows in the child table. Both ON DELETE
CASCADE and ON UPDATE CASCADE are supported.
• Set Null- Delete or update the row from the parent table and automatically set
null in the matching rows in the child table.
• RESTRICT: Rejects the delete or update operation for the parent table.
CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL);
Example: 1:1 relation MANAGES is mapped by choosing the participating entity type DEPARTMENT
to serve in the role of S, because its participation in the MANAGES relationship type is total.
2. Merged relation option: An alternate mapping of a 1:1 relationship type is possible by merging
the two entity types and the relationship into a single relation.
3. Cross-reference or relationship relation option: The third alternative is to set up a third relation
R for the purpose of cross-referencing the primary keys of the two relations S and T representing
the entity types.
Slide
7- 22
Student Enroll Course