constraint level-mysql

Way:

Cascade method: When updating/deleting records on the parent table, update/delete the matching records of the child table synchronously 

Set null method: When updating/deleting records on the parent table, set the column of the matching record on the child table to null, but note that the foreign key column of the child table cannot be not null  

No action mode: If there is a matching record in the child table, update/delete operations are not allowed on the corresponding candidate key of the parent table  

Restrict mode: Same as no action, both check foreign key constraints immediately

Set default method (may be blank in the visualization tool SQLyog): When the parent table is changed, the child table sets the foreign key column to a default value, but Innodb cannot recognize it

code:

# on update cascade on delete set null
CREATE TABLE dept(
                     did INT PRIMARY KEY,		#部门编号
                     dname VARCHAR(50)			#部门名称
);

CREATE TABLE emp(
                    eid INT PRIMARY KEY,  #员工编号
                    ename VARCHAR(5),     #员工姓名
                    deptid INT,		  #员工所在的部门
                    FOREIGN KEY (deptid) REFERENCES dept(did)  ON UPDATE CASCADE ON DELETE SET NULL
    #把修改操作设置为级联修改等级,把删除操作设置为set null等级
);

INSERT INTO dept VALUES(1001,'教学部');
INSERT INTO dept VALUES(1002, '财务部');
INSERT INTO dept VALUES(1003, '咨询部');

INSERT INTO emp VALUES(1,'张三',1001); #在添加这条记录时,要求部门表有1001部门
INSERT INTO emp VALUES(2,'李四',1001);
INSERT INTO emp VALUES(3,'王五',1002);
# 更新的时候进行了级联更新
UPDATE dept
SET did = 1004
WHERE did = 1002;
# 删除时删除了dept表记录并将emp表对应外键置为null
DELETE FROM dept
WHERE did = 1004;

Guess you like

Origin blog.csdn.net/weixin_44285713/article/details/130729883