{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

MySQL Foreign Key (Lab2.4) - MySQL Foreign Key Summary in...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
MySQL Foreign Key Summary : in this tutorial, you will learn about MySQL foreign key and how to create, add, and drop foreign key constraints in MySQL. Introduction to MySQL foreign key A foreign key is a field in a table that matches a field of another table. A foreign key places constraints on data in the related tables that, which enables MySQL to maintain referential integrity. Let’s take a look at the following database diagram in the sample database . We have two tables: customers and orders . Each customer has zero or more orders and each order belongs to only one customer. The relationship between customers table and orders table is one-to-many, and it is established by a foreign key in the orders table specified by the customerNumber field. The customerNumber field in the orders table relates to the customerNumber primary key field in customers table. The customers table is called parent table or referenced table , and the orders table is known as child table or referencing table . A foreign key has not only one column but also a set of columns. The columns in the child table often refer to the primary key columns in the parent table. A table may have more than one foreign key, and each foreign key in the child table can have a different parent table.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
A row in the child table must contain values that exist in the parent table e.g., each order record in the orders table must have a customerNumber that exists in the customers table. Multiple orders can refer to the same customer therefore this relationship is called one (customer) to many (orders), or one-to-many. Sometimes, the child and parent table is the same table. The foreign key refers back to the primary key of the table e.g., the following employees table : The reportTo column is a foreign key that refers to the employeeNumber column which is the primary key of the employees table to reflect the reporting structure between employees i.e., each employee reports to anther employee and an employee can have zero or more direct reports. The reportTo foreign key is also known as recursive or self-referencing foreign key. Foreign keys enforce referential integrity that helps you maintain the consistency and integrity of the data automatically. For example, you cannot create an order for a non-existent customer.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}