How to create foreign key in MySQL?
A foreign key in MySQL is basically a column or group of columns in a table that does the work of linking to a column or group of columns in another table. This key generally places constraints on the data in the related table that usually allows MySQL to maintain referential integrity.
The relationship that exists between the customer's table and the Orders table is basically one-to-many. And this is the relationship that has been established by the foreign key in the orders table that has been specified by the customer number column.
The customer's table is also known as the parent table or referenced table, and the orders table is generally called as the child table or referencing table.
How to create Foreign Key?
In order to create this, the user has to use the basic syntax of defining a foreign key constraint in the CREATE TABLE or ALTER TABLE statement that is as depicted below:
[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (column_name, ...)
REFERENCES parent_table(colunm_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
In this above-mentioned syntax, the user has to first specify the name of the constraint that they want to create after the CONSTRAINT keyword. In case, the user omits the constraint name then the MySQL will automatically generate a name for the constraint.
Secondly, the user has to specify a list of comma-separated columns after the keywords. The name is generally optional and it is generated automatically in case the user skips it. In the third step, the user has to specify the parent table that is followed by a list of comma-separated columns to which the columns reference.
This is a very important topic in the whole of a subject and there are various things that can be learned to master it hence, the students or the programmers can opt for the MySQL Tutorial that will clear all the steps and the topics that are involved in this subject. Like the final step of how to create a foreign key.
Lastly and the final step involves specifying how this factor maintains the referential integrity that is between the child and parent tables with the help of ON DELETE and ON UPDATE clauses.
Read More...
Also, Visit Here MySQL Tutorial for Beginners
Comments
Post a Comment