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

(多对多关系)

马克-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的学生显示出来。

详情请见:http://www.mark-to-win.com/index.html?content=Mydb/DBUrl.html&chapter=Mydb/DBIntroduction_web.html#ManyToMany

猜你喜欢

转载自blog.csdn.net/mark_to_win/article/details/84523286