mysql第六天:约束

一、约束

1、概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据

2、目的:保证数据库中数据的正确性,有效性和完整性

3、分类:

注意:约束是作用于表中字段上的,可以在创建表、修改表的时候添加约束

二、根据需求完成表的创建

create table user(
    id int primary key auto_increment comment 'ID',
    name varchar(10) not null unique comment '姓名',
    age int check ( age>0 && age<=120 ) comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
)comment '用户表';

1、主键自动增长的实现

并没有插入id的值,但是id可以进行自动增长

insert into user(name, age, status, gender)
values('xhm1',18,'1','女'),('xhm2',18,'1','女');

2、name不为空且唯一

3、年龄需要大于0小于等于120

4、默认值

insert into user(name, age, gender)
values('xhm4',24,'女');

三、外键约束

1、概念:外键是用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性

创建两张表为实例:

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

insert into employ(name,age, job, salary, entrydate, managerid, dept_id)
VALUES ('金庸',66,'总裁',20000,'2000-01-01',null,5),
       ('张无忌',20,'项目经理',12500,'2005-12-01',1,1),
       ('杨晓',33,'开发',8400,'2000-11-12',2,1),
       ('韦一笑',48,'开发',11000,'2002-05-01',2,1),
       ('常遇春',43,'开发',10500,'2004-09-07',3,1),
       ('小赵',19,'人事',5000,'2023-08-08',2,1);

create table dept(
    id int auto_increment comment 'ID' primary key ,
    name varchar(20) not null comment '部门名称'
)comment '部门分类';

insert into dept(name) values ('研发部'),('市场部'),('财务部'),('销售部'),('总经办');

2、语法:添加外键

create table 表名(

        字段名 数据类型,

        ...

        [constraint] [外键名称] foreign key(外键字段名)  references 主表(主表列名)

);

alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);

为上面的两张表添加外键

alter table employ add constraint fk_employ_dept_id foreign key (dept_id) references dept(id);

删除外键:

alter table 表名 drop foreign key 外键名称;

alter table employ drop foreign key fk_employ_dept_id;


 

4、删除/更新行为

alter table 表名 add constraint 外键名称 foreign key(外键字段) references 主表名(主表字段名) 
on update cascade on delete cascade;
alter table employ add constraint  fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade;




alter table employ add constraint  fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null ;


  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值