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

What is the role of mysql foreign key constraints

王林
Release: 2023-06-03 13:40:04
forward
1902 people have browsed it

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); -- 主表(列名)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template