您的位置:首页 > 其它

多表查询信息

2016-02-04 21:26 232 查看
## 多表信息查询 ##

多表的信息的查询涉及到第三方表的构建,一般来说会把两个目标表的主键作为这个第三方表的联合外键进行设置,并添加外约束。现如果想进行多表查询如查询教师编号为XX的所有的学生的信息,就可以使用

该操作的前提是数据库中已经按照规则设计好了数据库表。

"select s.* from teacher_student ts , student s where ts.teacher_id =? and ts.student_id = s.id"


细节描述:

这句SQL语句的含义如下:

先是
select * from teacher_student where teacher_id =?


然后给teacher_student取个别名,方便后续的操作,即
select * from teacher_student ts where ts.teacher_id = ?


再就是怎么将两个表联系起来的实现,即
select * from teacher_student ts ,student s where ts.teacher_id = ?


这样仍然是不够的,要想取出学生数据还应还进一步约束,即
select * from teacher_student ts ,student s where ts.teacher_id = ? and ts.student_id = s.id


这样就结束了吗?不,上面那个sql语句获得的是两个表的联合结果,要想获得学生信息,还应该进一步的对sql语句进行优化。即
select s.* from teacher_student ts,student s where ts.teacher_id = ? and ts.student_id = s.id
,好了这样就大功告成了。

至此,便可以简单的从多对多的数据库表中实现多表信息查询的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: