MySQL学习-基础篇-约束-概述

目录

p32-基础-约束-概述

p33-基础-约束-演示

p34-基础-约束-外键约束

p35-基础-约束-外键删除更新行为

p36-基础-约束-小结


p32-基础-约束-概述

p33-基础-约束-演示

create table user(
    id int primary key auto_increment comment '主键',
    name varchar(10) not null unique comment '姓名',
    age int check ( age>0 and age<=120 ) comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
) comment '用户表';
-- 插入数据 验证
insert into user(name, age, status, gender) VALUES ('tom1',19,'1','男'), ('tom2',25,'0','男');
insert into user(name, age, status, gender) VALUES ('tom3',19,'1','男')

insert into user(name, age, status, gender) VALUES (null,19,'1','男');
insert into user(name, age, status, gender) VALUES ('tom3',19,'1','男');

insert into user(name, age, status, gender) VALUES ('tom4',80,'1','男');
insert into user(name, age, status, gender) VALUES ('tom5',-1,'1','男');
insert into user(name, age, status, gender) VALUES ('tom5',121,'1','男');

insert into user(name, age, gender) VALUES ('tom5',120,'男');

p34-基础-约束-外键约束

-- 准备数据
create table dept(
    id   int auto_increment comment 'ID' primary key ,
    name varchar(50) not null comment '部门名称'
)comment '部门表';
insert into dept (id, name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');

删除了id为1的。

 

create table emp(
    id int auto_increment comment 'ID' primary key ,
    name varchar(50) not null comment '姓名',
    age int comment '年龄',
    job varchar(20) comment '职位',
    salary int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id int comment '部门ID'
)comment '员工表';

insert into emp (id, name, age, job, salary, entrydate, managerid, dept_id) values
            (1,'金庸',66,'总裁',20000,'2000-01-01',null,5),(2,'张无忌',20,'项目经理',12500,'2005-12-05',1,1),
            (3,'杨瑶',33,'开发',8400,'2000-11-03',2,1),(4,'韦一笑',48,'开发',11000,'2002-02-05',2,1),
            (5,'常遇春',43,'开发',10500,'2004-09-07',3,1),(6,'小邵',19,'网络',6600,'2004-10-12',2,1);

 

-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

alter table emp drop foreign key fk_emp_dept_id;

 蓝色小钥匙消失

p35-基础-约束-外键删除更新行为

-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;

p36-基础-约束-小结

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值