This relationship allows the employees table to store the reporting structure between employees and managers. The reportTo column is a foreign key that refers to the employeeNumber column which is the primary key of the employees table. See the following employees table from the sample database. In this case, the foreign key references back to the primary key within the same table. Sometimes, the child and parent tables may refer to the same table. Multiple rows in the orders table can have the same customerNumber. Once a foreign key constraint is in place, the foreign key columns from the child table must have the corresponding row in the parent key columns of the parent table or values in these foreign key column must be NULL (see the SET NULL action example below).įor example, each row in the orders table has a customerNumber that exists in the customerNumber column of the customers table. Typically, the foreign key columns of the child table often refer to the primary key columns of the parent table.Ī table can have more than one foreign key where each foreign key references to a primary key of the different parent tables. The customers table is called the parent table or referenced table, and the orders table is known as the child table or referencing table. The customerNumber column in the orders table links to the customerNumber primary key column in the customers table. And this relationship is established by the foreign key in the orders table specified by the customerNumber column. The relationship between customers table and orders table is one-to-many. In this diagram, each customer can have zero or many orders and each order belongs to one customer. Let’s take a look at the following customers and orders tables from the sample database. The foreign key places constraints on data in the related tables, which allows MySQL to maintain referential integrity. Introduction to MySQL foreign keyĪ foreign key is a column or group of columns in a table that links to a column or group of columns in another table. Summary: in this tutorial, you will learn about MySQL foreign key and how to create, drop, and disable a foreign key constraint.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |