Creating foreign key constraints in MySQL can force sub-table records to be associated with main table records to ensure data integrity. Specific steps include: 1. Specify the foreign key column of the subtable; 2. Reference the unique index column of the main table; 3. Set up cascade delete or update operations (optional).
A foreign key constraint is a database constraint used to ensure the integrity of data in a table. It forces each record in the child table to reference an existing record in the main table.
In MySQL, you can create a foreign key constraint by specifying the foreign key constraint when creating the child table. The syntax is as follows:
<code class="sql">CREATE TABLE child_table ( child_column INT NOT NULL, PRIMARY KEY (child_column), FOREIGN KEY (child_column) REFERENCES parent_table (parent_column) );</code>
where:
child_table
is the name of the child table. parent_table
is the name of the main table. child_column
is a foreign key column in the child table. parent_column
is the reference column in the main table. After a foreign key constraint is created, the following rules will be enforced:
There are many benefits of using foreign key constraints:
ON DELETE CASCADE
and ON UPDATE CASCADE
options Delete and update operations. The above is the detailed content of How to create foreign key constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!