当前位置: 首页 > news >正文

MySQL-20.多表设计-一对一多对多

一.一对一

在数据的一对一关系中,可以在任意一个数据表中添加对另一个表的外键约束,但是该外键约束必须是unique的,否则无法实现一对一关系。

create table tb_user(id int unsigned  primary key auto_increment comment 'ID',name varchar(10) not null comment '姓名',gender tinyint unsigned not null comment '性别, 1 男  2 女',phone char(11) comment '手机号',degree varchar(10) comment '学历'
) comment '用户信息表';insert into tb_user values (1,'白眉鹰王',1,'18812340001','初中'),(2,'青翼蝠王',1,'18812340002','大专'),(3,'金毛狮王',1,'18812340003','初中'),(4,'紫衫龙王',2,'18812340004','硕士');create table tb_user_card(id int unsigned  primary key auto_increment comment 'ID',nationality varchar(10) not null comment '民族',birthday date not null comment '生日',idcard char(18) not null comment '身份证号',issued varchar(20) not null comment '签发机关',expire_begin date not null comment '有效期限-开始',expire_end date comment '有效期限-结束',user_id int unsigned not null unique comment '用户ID',constraint fk_user_id foreign key (user_id) references tb_user(id)
) comment '用户信息表';insert into tb_user_card values (1,'汉','1960-11-06','100000100000100001','朝阳区公安局','2000-06-10',null,1),(2,'汉','1971-11-06','100000100000100002','静安区公安局','2005-06-10','2025-06-10',2),(3,'汉','1963-11-06','100000100000100003','昌平区公安局','2006-06-10',null,3),(4,'回','1980-11-06','100000100000100004','海淀区公安局','2008-06-10','2028-06-10',4);

 二.多对多

create table tb_student(id int auto_increment primary key comment '主键ID',name varchar(10) comment '姓名',no varchar(10) comment '学号'
) comment '学生表';
insert into tb_student(name, no) values ('黛绮丝', '2000100101'),('谢逊', '2000100102'),('殷天正', '2000100103'),('韦一笑', '2000100104');create table tb_course(id int auto_increment primary key comment '主键ID',name varchar(10) comment '课程名称'
) comment '课程表';
insert into tb_course (name) values ('Java'), ('PHP'), ('MySQL') , ('Hadoop');create table tb_student_course(id int auto_increment comment '主键' primary key,student_id int not null comment '学生ID',course_id  int not null comment '课程ID',constraint fk_courseid foreign key (course_id) references tb_course (id),constraint fk_studentid foreign key (student_id) references tb_student (id)
)comment '学生课程中间表';insert into tb_student_course(student_id, course_id) values (1,1),(1,2),(1,3),(2,2),(2,3),(3,4);

 


http://www.mrgr.cn/news/54216.html

相关文章:

  • 每日一道算法题(Leetcode 20)
  • 抖音列表页采集-爬虫部分(2)
  • 在wpf 中 用mvvm 的方式 绑定 鼠标事件
  • 51单片机快速入门之 IIC I2C通信
  • 【机器学习】VQ-VAE(Vector Quantized Variational Autoencoder)
  • Spring Boot 核心理解-自定义Starter
  • 解锁A/B测试:如何用数据驱动的实验提升你的网站和应用
  • 速盾:为什么高防cdn比普通cdn效果更好?
  • 利士策分享,财富与福报,有没有内在联系?
  • 【Macbook air 2017 升级换硬盘遇到的问题】
  • Thread类的介绍
  • 简历怎么写?怎么准备面试?怎么让面试官感兴趣?
  • 快速查看平台信息脚本(完善中...)
  • Javaweb基础-vue
  • 1024程序员节 我们在 上海-RAG学习
  • Lua数字
  • UDP协议和TCP协议
  • GESP CCF python六级编程等级考试认证真题 2024年9月
  • FFMPEG录屏(19)--- 枚举Windows下的屏幕列表,并获取名称、缩略图
  • 动态规划知识简记
  • ARM/Linux嵌入式面经(四六):华为
  • 识别NPD自恋者的伪装:10个关键特征,助你远离吸血鬼的围猎
  • 不收费的数据恢复工具有哪些好用?快来看这五款:
  • 硅基流动多模型工作流应用平台,免费2000万Token来了
  • 两阶段提交(2PC)如何保证一致性
  • 鸿蒙系统 VS 安卓系统,谁将引领未来移动操作系统?