INSERT into Employee VALUES (102, 'Pranaya', 32000, 20) INSERT into Employee VALUES (101, 'Anurag', 25000, 10) In our case both columns having the same INT data type. Note: The DepartmentId column of the Employee table and Id column of the Department table must have the same data type otherwise foreign key relationship is not possible. You can verify the same by exploring the Foreign Keys folder as shown in the below image. Once you execute the above CREATE Table Statements, the Employee table is created with the Foreign Key Constraints. CREATE TABLE EmployeeįOREIGN KEY (DepartmentId) REFERENCES Department(Id) Further, if you notice in the below query, we have marked the DepartmentId column as the FOREIGN KEY which referencing the Id column of the Department table. This table is going to be our foreign ley table. Now create another table with the name Employee by using the FOREIGN KEY constraint. INSERT INTO Department (Id, Name, Location) VALUES (30, 'Finance', 'Mumbai') INSERT INTO Department (Id, Name, Location) VALUES (20, 'HR', 'Delhi') INSERT INTO Department (Id, Name, Location) VALUES (10, 'IT', 'Hyderabad') Once you created the Department table, now insert some master data into this table by executing the below SQL Script. Here, we created the reference column (Id) using the Primary Key constraint. This table is going to be the parent table or master table which contains the reference key column. First, create a table with the name Department by using the PRIMARY KEY constraint by executing the below CREATE Table query. Let us understand how to create the primary key and foreign key relationship between two tables in MySQL. Examples to understand FOREIGN KEY Constraints in MySQL. ![]() If the above points are not clear at the moment, then don’t worry, we will try to explain all the above points with examples. The common column which is present in the child or detailed table is known as the Foreign key column and we need to impose a Foreign key constraint on the column which refers to the reference key column of the master table.So, we need to impose either UNIQUE or PRIMARY key constraint on that column. The common column that is present under the parent table or master table is known as the reference key column and moreover, the reference key column should not contain any duplicate values. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |