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].
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 constraintsForeign 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 data2. Add foreign key constraints to existing fields-- 为cls_id字段添加外键约束 alter table students add foreign key(cls_id) references classes(id); 【首先会验证的,不符合就会报错】
-- 创建学校表 create table school( id int not null primary key auto_increment, name varchar(10) );
-- 创建老师表 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) );
-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称 show create table teacher;
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!