Foreign keys in SQL

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Foreign key

concept:

     The primary key and a foreign key, the primary action is the relationship between foreign key so that the data tables in better correlation.

Foreign key features:

     From a reference value table is a foreign key to the master table primary key.

     From the type of the foreign key table, the primary table must be consistent with the type of the primary key.

Role : foreign keys can ensure the integrity and consistency of the data

Format: (two kinds)

[constraint 外键约束关系的名称] foreign key 从表(外键字段名称) references 主表(主键字段名称)
alter table 从表 add [constraint] [外键名称] foreign key (从表外键字段名) references 主表 (主表的主键);

egg:

data:

#部门表:
CREATE TABLE dept(
id INT PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(20) UNIQUE NOT NULL,
dcode INT UNIQUE NOT NULL);
#员工表:
CREATE TABLE emp(
id INT PRIMARY KEY AUTO_INCREMENT,
ename VARCHAR(20) NOT NULL,
ecode INT UNIQUE NOT NULL,
did INT,
CONSTRAINT dept_emp FOREIGN KEY emp(did) REFERENCES dept(id));

Insert data:

#插入数据:
INSERT INTO dept VALUES(NULL,'技术部',100);
INSERT INTO dept VALUES(NULL,'财务部',200);
INSERT INTO dept VALUES(NULL,'人事部',300);
INSERT INTO emp VALUES(NULL,'张三',123,1);
INSERT INTO emp VALUES(NULL,'李四',124,2);
INSERT INTO emp VALUES(NULL,'王五',125,1);
INSERT INTO emp VALUES(NULL,'田七',126,1);

Throw an exception:

问题:DELETE FROM dept WHERE id=1; 

Error Reason: Table id employees associated sectors of sector 1 INSERT INTO emp VALUES (NULL, ' haha', 127,5); wrong reasons: no primary key in the primary table id is the sector 5

Guess you like

Origin blog.csdn.net/longyanchen/article/details/93778930