当前位置:网站首页>[MySQL learning notes 18] constraints

[MySQL learning notes 18] constraints

2022-06-21 17:25:00 yqs_ two hundred and eighty-one million eight hundred and seven

Common constraints

 Insert picture description here

practice

create table stu(
    id int primary key auto_increment,
    name varchar(10) not null unique,
    age int check (age>=0 and age<=120),
    status char(1) default 1,
    gender char(1) default ' male '
)
# Create department table 
create table dept(
    id int primary key auto_increment,
    name varchar(20) not null
);
# insert data 
insert into dept(id,name) value (1,' R & D department '),(2,' The Marketing Department '),(3,' Finance Department '),(4,' The sales department '),(5,' General Manager's Office ');
# Create an employee table 
create table emp(
    id int primary key auto_increment,
    age int,
    job varchar(20),
    salary int,
    entry_date date,
    manager_id int,
    dept_id int,
    constraint fk_emp_dept_id foreign key (dept_id) references dept(id)
);
# Delete foreign key 
alter table emp drop foreign key fk_emp_dept_id;
# Add foreign keys 
alter table emp add constraint foreign key (dept_id) references dept(id);

Foreign key delete / Update behavior

name explain
NO ACTION/RESTRICT( Default behavior ) Reject the operation when the updated record is deleted and referenced by a foreign key
CASCADE When the deleted updated record is referenced by a foreign key , At the same time, delete and update the record corresponding to the foreign key
SET NULL When the deleted updated record is referenced by a foreign key , Set the referenced record foreign key value to null
SET DEFAULT In the same way as above , Set to default (innodb Engine not supported )

grammar
alter table Table name add constraint Foreign key name foreign key ( Foreign key field ) references Table name ( Field name ) on update cascade on delete set null;

原网站

版权声明
本文为[yqs_ two hundred and eighty-one million eight hundred and seven]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211409238365.html