0
点赞
收藏
分享

微信扫一扫

使用同步和异步方式更新插入MongoDB数据的性能对比

你的益达233 2024-06-14 阅读 10

文章目录


四、约束

4.1 概述

  • 概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。
  • 目的:保证数据库中数据的正确、有效性和完整性。
  • 分类:

在这里插入图片描述

4.2 约束演示

  • 根据需求,完成表的创建

在这里插入图片描述

create table test1(
    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 '用户表';

4.3 外键约束

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

在这里插入图片描述

  • 注意:目前上述的两张表,在数据库层面并未建立外键关联,所以是无法保证数据的一致性和完整性的。

  • 语法:

-- 创建表时添加外键
create table 表名(
	字段名 数据类型,[constraint] [外键名称] foreign key (外键字段名) references 主表(主表列名)
);
-- 添加字段约束时添加外键
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);
-- 删除外键
alter table 表名 drop foreign key 外键名称;
  • 案例在员工表的部门id与部门表的id添加外键
-- 案例在员工表的部门id与部门表的id添加外键
create table dept(
    id int primary key auto_increment comment 'ID',
    name varchar(58) not null comment '部门名称'
) comment '部门表';
insert into dept(id, name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');
select * from dept;

create table emp (
    id int primary key auto_increment comment 'ID',
    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(name, age, job, salary, entrydate, managerid, dept_id) VALUES ('金庸',66,'总裁',20000,'2000.1.1',null,5),
                                                                              ('张无忌',20,'项目经理',12500,'2005.12.05',1,1),
                                                                              ('杨逍',33,'开发',8400,'2000.11.3',2,1),
                                                                              ('韦一笑',48,'开发',11000,'2002.2.5',2,1),
                                                                              ('常遇春',43,'开发',10500,'2004.9.7',3,1),
                                                                              ('小昭',19,'程序员鼓励师',6600,'2004.10.12',2,1);
select * from emp;
-- 添加外键约束
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
  • 删除/更新行为

在这里插入图片描述

  • 语法:
alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update cascade on delete cascade;

总结

在这里插入图片描述

举报

相关推荐

0 条评论