Home > Database > SQL > How to set foreign keys in database sql statement

How to set foreign keys in database sql statement

coldplay.xixi
Release: 2023-01-13 00:40:46
Original
80972 people have browsed it

Methods for setting foreign keys in database sql statements: 1. Add foreign key constraints [alter table add foreign key (foreign key field) references from table main table (primary key field)]; 2. Delete foreign key constraints [ alter table table name drop foreig].

How to set foreign keys in database sql statement

The operating environment of this article: Windows 7 system, Microsoft SQL Server 2008 version, Dell G3 computer.

Recommended: sql video tutorial

##How to set foreign keys in database sql statement:

1. The function of foreign key constraints

Foreign key constraints: When updating and inserting the value of the foreign key field, it will be verified with the data of the field in the reference table. If the data is illegal, it will be updated and inserted. Will fail to ensure the validity of the data

2. Add foreign key constraints to existing fields

-- 为cls_id字段添加外键约束
alter table students add foreign key(cls_id) references classes(id);  【首先会验证的,不符合就会报错】
Copy after login

3. Set foreign key constraints when creating the data table

-- 创建学校表
create table school(
    id int not null primary key auto_increment, 
    name varchar(10)
);
Copy after login
-- 创建老师表
create table teacher(
    id int not null primary key auto_increment, 
    name varchar(10), 
    s_id int not null, 
    foreign key(s_id) references school(id)
);
Copy after login

4. Delete foreign key constraints

-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称
show create table teacher;
Copy after login
rrree

The above is the detailed content of How to set foreign keys in database sql statement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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