数据库表中多对多关系怎么设计?

(多对多关系) 

马克-to-win:Teacher表:两列id,name。
Studnet表: 三列:id,name,age
TeacherStudent表(关系表):三列:id,tid,sid

create table TeacherStudent(id int not null,tid int not null,sid int not null);

2) teacher and student:(一个老师可能有多个学生,一个学生可能有多个老师)

qixy有两个学生:liyaohua and fuwenlong, huanglaosh老师有一个学生--->fuwenlong

INSERT INTO TeacherStudent (id,tid,sid) VALUES(1,1,1);

INSERT INTO TeacherStudent (id,tid,sid) VALUES(2,1,2);

INSERT INTO TeacherStudent (id,tid,sid) VALUES(3,2,2);


qixy的学生显示出来。

select * from Teacher t,Student s,TeacherStudent ts where t.name='qixy' and t.id=ts.tid and s.id=ts.sid;

+----+------+----+-----------+------+----+-----+-----+
| id | name | id | name      | age  | id | tid | sid |
+----+------+----+-----------+------+----+-----+-----+
|  1 | qixy |  1 | liyaohua  |   25 |  1 |   1 |   1 |
|  1 | qixy |  2 | fuwenlong |   26 |  2 |   1 |   2 |
+----+------+----+-----------+------+----+-----+-----+

 

huanglaosh的学生显示出来。

select * from Teacher t,Student s,TeacherStudent ts where t.name='huanglaosh' and t.id=ts.tid and s.id=ts.sid;

+----+------------+----+-----------+------+----+-----+-----+
| id | name       | id | name      | age  | id | tid | sid |
+----+------------+----+-----------+------+----+-----+-----+
|  2 | huanglaosh |  2 | fuwenlong |   26 |  3 |   2 |   2 |
+----+------------+----+-----------+------+----+-----+-----+

fuwenlong的老师显示出来。

select * from Teacher t,Student s,TeacherStudent ts where s.name='fuwenlong' and t.id=ts.tid and s.id=ts.sid;

+----+------------+----+-----------+------+----+-----+-----+

| id | name       | id | name      | age  | id | tid | sid |
+----+------------+----+-----------+------+----+-----+-----+
|  1 | qixy       |  2 | fuwenlong |   26 |  2 |   1 |   2 |
|  2 | huanglaosh |  2 | fuwenlong |   26 |  3 |   2 |   2 |
+----+------------+----+-----------+------+----+-----+-----+

参考一下以下游动的同等写法:(未来springJdbc或mybatisxxxxx的某种技术中也许用的着,因为它严格限制单表游动)

select name from Student where id in (select sid from TeacherStudent  where tid in (select id from Teacher where name='qixy')) ;

结果:

+-----------+
| name      |
+-----------+
| liyaohua  |
| fuwenlong |
+-----------+

 

更多请看下节:http://www.mark-to-win.com/tutorial/mydb_DBIntroduction_ManyToMany.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值