Sql Query从关联表中获取数据

时间:2013-06-18 09:32:16

标签: sql relation jointable

我必须从两个表中获取数据 (PK)=主键
(FK)=外键

TABLE1- [STUDENTS]
s_id(PK)     name    other
1             a        z
2             b        z
3             c        z

TABLE2- [CLASSES]
c_id(PK)  class_name
1           5th
2           6th
3           7th

TABLE3- [STUDENT-CLASS]
id(PK)    student_id(FK)     class_id(FK)
1            1                1
2            1                2

3            2                1
4            2                2

5            3                1

6            1                3

我想向学生展示当前班级(最后指定的班级)
表关系为
当学生被录取时,它被分配到1级 1年后,在[学生 - 课程]表格中插入新记录,为每个或某个学生分配新课程 我希望像这样显示

s_id       name    other     [STUDENT-CLASS].Class_id    [CLASSES].class_nam
1         a        z                  3                        7th
2         b        z                  2                        6th
3         c        z                  1                        5th

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

Select S.studentid, s.name, s.other, c.classid, c.classname
 from 
 (Select studentid, Max(Classid) as 'currentclassid' from StudentClassTable group by studentid) A
  inner join StudentTable S on A.studentid = S.Studentid 
  inner join ClassTable C on A.CurrentClassid = C.Classid

答案 1 :(得分:0)

以下查询将完成此任务。

SELECT student_id, name, other, b.last_class_id, c.class_name
FROM STUDENTS a
LEFT JOIN (SELECT student_id, max(class_id) As last_class_id 
           FROM student_class
           GROUP BY student_id) b ON a.student_id = b.student_id
LEFT JOIN CLASSES c ON c.class_id = b.last_class_id