数据库中几个表之间的关联查询


在数据库操作中,有很多时候不是对某一个表进行数据库操作, 通常还会把其他表的字段的值也传递过来。不过这连个表不是没有关系的。通常通过索引或者健关联起来

如下为一个例子。

表一。表名称 tb1. 其中 studentID 为主索引。外健。

studentID

|

studentName

|

studentGender

|

studntAge

---|---|---|---

3102079014

|

刘永相

|

|

25

3102079015

|

赵某某

|

|

23

表二。表名称 tb2. 其中 teacherID 为主索引。外健。

teacherID

|

teacherName

|

teacherManageStudent

|

teacherMemo

---|---|---|---

3645221

|

刘刚

|

3102079014

|

备注无

3645222

|

成昆

|

3102079015

|

备注无

现在有一个查询,需要知道某一个老师管理的学生的名字。由表二可以知道老师刘刚管理的是 3102079014 这个学生,又由表 1 知道 3102079014 这个学生的名称为刘永相。怎么写这个查询语句呢?

如下:

sql=”select tb2.teacherName,tb1.studentName for tb2,tb1 where tb2.teacherManageStuent=tb1.studentID”

出来的结果为:

teacherName

|

studentName

---|---

刘刚

|

刘永相

可能读者马上就会产生一个疑问,在表 2 里头。 teacherID 作为索引,必然只有唯一的一个 ID 记录。那么我怎么来管理所有的学生呢?

由两个处理的方法。 1 :在 teacherManageStudent 字段里头把所有的学生的 ID 都录进去。中间用!或者其他符号表示出来,在后面的 sql 生成的时候,用一个循环来不断地把所有的学生得 ID 都写入 sql. : 2 : tb2 不要建成如上的形式,在 tb2 里放置老师的基本信息。另外一个新表里头放置的老师的 ID 和老师管理学生 ID 的记录,如下:

新表:表名称 tb3

teacherID

|

teacherManageStudent

---|---

3645221

|

3102079014

其中表 2 变成了

teacherID

|

teacherName

|

teacherMemo

---|---|---

3645221

|

刘刚

|

备注无

3645222

|

成昆

Published At
Categories with 数据库类
comments powered by Disqus