(多对多关系)
马克-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 |
+-----------+
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44591615/article/details/109205764
相关文章
- 12-01hibernate- Hibernate中多对多的annotation的写法(中间表可以有多个字段)
- 12-01sql-此查找(关联)表正确吗? (多对多关系)
- 12-01(八)Django学习——常用的查询数据的方法以及查询条件;常用的字段类型映射关系,字段类型及Field的常用参数;Django的表关系的实现(一对多,一对一,多对多))
- 12-01(九)Django学习——一对一,一对多,多对多关系表的各种数据操作;跨关联关系的多表查询!
- 12-01数据库表设计:一对一、一对多、多对多
- 12-01EF更新多对多关系表中记录的时候,无法更新关系表的问题。
- 12-01测试开发22---Django单元测试与表多对多关系丨蓄力计划
- 12-01flask中的关联关系:一对多
- 12-01测试开发22---Django单元测试与表多对多关系丨蓄力计划
- 12-01django外键三种多对多关系表的创建