2013-06-18 81 views
0

得到的数据我必须从两个表
(PK)=主键
(FK)=外键SQL查询,从关联表

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 

我想显示当前班的学生(最后分配的班级)
个 表关系是
当学生得到承认,这是一个新的记录插入[学生-CLASS]表中的每个或一些学生分配新的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 
+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 
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