Sql2000数据库多表查询【这个问题值50分】
来源:百度知道 编辑:UC知道 时间:2024/06/21 08:27:08
我要查询User_id为Tom的 crname,cyear,score
其实这个sql语句还不麻烦。写sql我都是按照以下几步来做(对于比较麻烦的)
1.列出所有需要的字段
select crname,cyear,score from tabcour,tabstu_cour,tabstu
2.找它们之间的关系
where tabstu.sid = tabstu_cour.sid and tabstu_cour.crid = tabcour.crid
3.写条件 and tabstu.user_id='Tom'
其实关键是第2步,上面写法的思路是这样:从tabstu中找到Tom,然后到tabstu_cour中找他的成绩(用sid关联);后面还要列出其课程名称,而这又存在tabcour中,它跟tabstu-cour有关联,所以它们之间根据crid关联。
当然,还有另外一种更直观的写法,就是反过来考虑。从tabstu_cour向两边考虑,要显示crname,它在tabstu中于是关联,要使用查询条件user_id='Tom'而user_id在tabstu中于是关联。
最后:现在多数人在开发时用join on的写法。也可以改成:
select crname,cyear,score
from tabstu_cour
join tabcour on tabstu_cour.crid = tabcour.crid
join tabstu on tabstu.sid = tabstu_cour.sid
where tabstu.user_id like 'Tom'
注意:Tom应该用单引号
select crname,cyear,score
from tabcour join tabstu_cour
on tabcour.crid=tabstu_cour.crid
join tabstu
on tabstu_cour.sid=tabstu.sid
where tabstu.user_id=&quo