一起加入两个查询

时间:2011-04-25 14:05:39

标签: mysql sql inner-join

我有一个数据库,其中包含以下表格中的大量学生信息

Student:
    id
    created_on
    updated_on

StudentHistory
    id
    studentid
    schoolid
    gradeid
    datestamp
    active

学生历史管理学生多年来的变化,并允许我报告学生的成长情况。

我现在需要执行以下查询:

SELECT * FROM students
INNER JOIN studenthistory
    ON student.id = studenthistory.studentid
WHERE studenthistory.active = 1

问题是查询不必像我需要的那样提取最新的历史记录。有没有办法可以保证只有最新的历史记录会被加入?

2 个答案:

答案 0 :(得分:4)

SELECT  *
FROM    students s
JOIN    studentshistory sh
ON      sh.id =
        (
        SELECT  shi.id
        FROM    studentshistory shi
        WHERE   shi.studentid = s.id
                AND shi.active = 1
        ORDER BY
                studentid DESC, active DESC, datestamp DESC, id DESC
        LIMIT 1
        )

studentshistory (studentid, active, datestamp, id)上创建一个索引,以便快速工作。

答案 1 :(得分:0)

我认为这应该有效:

SELECT * FROM Students
INNER JOIN StudentHistory sh1 
  ON Student.studentid = sh1.studentid 
  AND StudentHistory.datestamp = 
    (SELECT MAX(datestamp) 
     FROM StudentHistory sh2 
     WHERE sh2.studentid = sh1.studentid);