数据库设计中表之间的关系(1:1 1:N N:N)和在数据库中的实现

1)数据库的设计
	(1)表的关系
	(2)设计准则
	
2)多表之间的关系 及其 在数据库中的实现
	(1)1对1: 如人和身份证   --> 不常见
	student学生表
	id     name       age    cid(这个要外键唯一)
	1      洪七公     85	  1
	2	   周伯通     75	  2
	
	
	card身份证表
	id        number
	1		 612243234
	2        523241423
	
	
	解决办法:可以在任意的一方添加外键 指向 另一方的主键 
	
	
	(2)1对多 多对1: 部门和员工,一个部门有多个员工, 一个员工只能有一个部门:
		emp 员工表n:
		eid 		name		 age		dept_id(外键)
		1			张无忌		 18			2
		2			令狐冲		 18			2
		3			郭靖		 38			1
		
		dept 部门表1:
		did    	name
		1		财务部
		2		销售部
		
		解决办法: 
			在emp添加外键dept_id指向部门表的did(在多的一方建立外键 指向 1的一方的主键);
			
		
	(3)多对多: 学生和课程,1个学生可以选择多门课程,一个课程可以被多个学生选择;
		student学生表
		sid 	name	  age
		1        赵敏     17
		2        周芷若   18
		3	     黄蓉     38
		
		
		class课程表
		cid         name
		1		    英语
		2			数学
		
		
		t_student_class中间表 
			
			
		sid      cid
		1		  1
		1		  2
		3		  2
		
		
		
		解决方案: 
			多对多的关系实现必须通过第三张中间表;
			第3张表必须有2个字段以外键的形式分别指向 student的主键和class的主键;
			联合主键;
		
		
		
3)实战(旅游线路分类  旅游线路  用户)
	(1)分类
		cid  name
		
	(2)线路表
		rid    name  price
	
	
	(3)用户表
	id      username     password


	说明:
		1个分类对应多个线路: 比如蜜月游包含很多个线路: 分类--> 线路  1:N
		
		一个用户有多个线路, 1个线路也可以有多个用户:  线路表<--> 用户  N:N
			中间表:
				rid   uid
		
		
	实现:
		-------分类表-------
		create table tab_category(
			cid int primary key auto_incrment,
			cname varchar(100) not null unique
		);
		
		insert into tab_category(cname) values('周边游'), ('出境游'), ('国内游'), ('港澳游');
		
		select * from tab_category;
		
		-------线路表-------
		create table tab_route(
			rid int primary key auto_increment,
			rname varchar(100) not null unique,
			price double,
			rdate date,
			cid int,
			foreign key(cid) references tab_category(cid)  --简化写法,系统会分配一个唯一的外键名称
		);
		
		-------用户表-------
		create table tab_user(
			uid int primary key auto_increment,
			username varchar(100) unique not null,
			password varchar(30) not null,
			name varchar(100),
			birthday date,
			sex char(1) default '男',
			telephone varchar(11),
			email varchar(100)
		);

		-------用户表和线路表的N:N的中间表-------
		create table tab_favorite(
			rid int,
			date datetime,
			uid int,
			
			--创建符合主键
			primary key(rid, uid),
			foreign key (rid) references tab_route(rid),
			foreign key (uid) references tab_user(uid)
		);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值