Foreign key is a data integrity constraint in MySQL, which ensures that the subtable data is consistent with the main table by referencing the primary key column of the main table. The working principle of foreign code is as follows: ensure that the main table data referenced by the subtable exists. Cascade deletion: When the main table record is deleted, the related records of the sub-table are deleted in cascade. Cascade update: When the primary key of the main table is updated, the related records of the sub-table are cascade updated.
What is a foreign code in MySQL?
Foreign Key is a data integrity constraint in MySQL that is used to ensure that rows between different tables have valid and consistent relationships. It does this by referencing a primary key column in another table (the main table).
How do foreign codes work?
When a foreign key is created in a child table, it references the primary key column in the main table. When inserting a record into the child table, the value of the foreign key column must match the existing primary key value in the main table.
Create foreign code
Use the following syntax to create a foreign code:
<code class="sql">ALTER TABLE 子表 ADD FOREIGN KEY (外码列) REFERENCES 主表(主键列);</code>
Example
Suppose we have two tables: Order
and Order Details
. The Order Details
table has a foreign key order_id
, which refers to the primary key id
in the Order
table.
<code class="sql">CREATE TABLE 订单 ( id INT PRIMARY KEY, 客户名称 VARCHAR(255) ); CREATE TABLE 订单明细 ( id INT PRIMARY KEY, order_id INT, 产品名称 VARCHAR(255), 数量 INT, FOREIGN KEY (order_id) REFERENCES 订单(id) );</code>
When inserting a record into the order details
table, the order_id
must correspond to an existing id## in the
orders table # value. This ensures that order details are always associated with a valid order.
The above is the detailed content of What is mysql Chinese and foreign code?. For more information, please follow other related articles on the PHP Chinese website!