close[x]


MySQL

MySQL-Home MySQL-Environment setup MySQL- Workbench MySQL-Basic syntax MySQL-Operator MySQL-Data type MySQL-Comments MySQL-Create DB MySQL-Drop DB MySQL-Select DB MySQL-Create Table MySQL-Drop table MySQL-Truncate MySQL-Primary Key MySQL-Foreign Key MySQL-Null MySQL-Increment MySQL-Having MySQL-Top MySQL-Insert Statement MySQL-Select Statement MySQL-Alter Statement MySQL-Where MySQL-And & Or MySQL-Default values MySQL-Exists MySQL-Order by MySQL-View MySQL-Update Statement MySQL-Delete Statement MySQL-Like MySQL-Sort MySQL-Limit MySQL-Min MySQL-Max MySQL-Group MySQL-In MySQL-Between MySQL-Union MySQL-Count MySQL-Average MySQL-Sum MySQL-Date & Time MySQL-Import MySQL-Export MySQL-Index MySQL-Temporary MySQL-Join MySQL-Full Join MySQL-Inner Join MySQL-Left Join MySQL-Right Join MySQL-Store Procedure MySQL-Injection MySQL-PHP connection



learncodehere.com




MySQL - FOREIGN KEY

A foreign key is a field or a column that is used to establish a link between two tables.

A foreign key in one table used to point primary key in another table.


Syntax : FOREIGN KEY


CREATE TABLE table_name (
column1 data_type(size) 

 column2 data_type(size)  
 PRIMARY KEY (columns),
 FOREIGN KEY (column) REFERENCES Persons(column)
);

The following MySQL creates a FOREIGN KEY on the "ROLL_NO" column when the "Teachers" table is created:


Example : FOREIGN KEY


 CREATE TABLE Teachers
 (
 TECH_NO int(3) NOT NULL ,
 NAME varchar(20) NOT NULL,
 SUBJECT varchar(20) ,
 PRIMARY KEY (TECH_NO),
 FOREIGN KEY (ROLL_NO) REFERENCES Students(ROLL_NO)
 );   

This would produce the following result.

mysql foreign key

The "ROLL_NO" column in the "Teachers" table points to the "ROLL_NO" column in the "Students" table.

The "ROLL_NO" column in the "Students" table is the PRIMARY KEY in the "Students" table.

The "ROLL_NO" column in the "Teachers" table is a FOREIGN KEY in the "Teachers" table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.



SQL FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "ROLL_NO" column when the "Teachers" table is already created, use the following MySQL:


Example :


ALTER TABLE Teachers
ADD FOREIGN KEY (ROLL_NO) REFERENCES Students(ROLL_NO);  

DROP aFOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following MySQL:


Example :


ALTER TABLE Teachers
DROP FOREIGN KEY ROLL_NO; 

Sample data for Students and Teachers table

Table : Students

ROLL_NO NAME SUBJECT
1 Will C++
2 SAM Python
3 Rani Node.js
4 Rim Java
5 Micheal JAVA
6 Lara PHP

Table : Teachers

TECH_NO NAME SUBJECT ROLL_NO
20 Kayla PHP 6
21 Albert Java 2
21 Albert Java 5
22 Helen Node.js 3
23 Anne Python 2
24 Jaime C++ 1

Sample Data Meaning

  • Students Lara's PHP Teachers name is 'Kayla'
  • Students Rani's Node.js Teachers name is 'Helen'
  • Students Rim ans Micheal's JAVA Teachers name is 'Albert'