Home  >  Article  >  Database  >  What is the role of mysql foreign key constraints

What is the role of mysql foreign key constraints

王林
王林forward
2023-06-03 13:40:041863browse

1. Foreign key constraints ensure the referential integrity between one or two tables. A foreign key is a reference relationship built between two fields of one table or two fields of two tables.

2. Ensure the integrity and accuracy of data between tables through foreign key constraints.

Example

-- 外键约束的操作
-- 关键字 foreighn key
-- 概述:就是让两个以及多个表之间建立联系
-- 创建表时加入外键
CREATE TABLE tab(
id int PRIMARY KEY ,
name VARCHAR(30),
t_id INT, -- 外键对应主表的主键 数据类型要一样
CONSTRAINT
    tab_tab1_id -- 外键名称
FOREIGN KEY
    (t_id) -- 外键列名
REFERENCES
    tab1(id) -- 主表(列名)
);
-- 第二张连接表
CREATE TABLE tab1(
id INT PRIMARY KEY , -- 主键id 也是连接tab表的外键
age INT
);
 
-- 删除外键约束
ALTER TABLE
    tab -- 表名
DROP FOREIGN KEY
    tab_tab1_id; -- 外键名称
 
-- 创建表后添加外键约束
ALTER TABLE
tab -- 从表
add CONSTRAINT
tab_tab1_id  -- 外键名
FOREIGN KEY
(t_id) -- 外键列名
REFERENCES
tab1(id); -- 主表(列名)

The above is the detailed content of What is the role of mysql foreign key constraints. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete