0

我必须从两个表
(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 在 [STUDENT-CLASS] 表格中插入新记录,为每个或一些学生分配新班级
我想这样显示

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
4

2 回答 2

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
于 2013-06-18T09:39:54.787 回答
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
于 2013-06-18T09:51:15.133 回答