如何从降序排序的记录中找到最后5条记录?

时间:2014-04-23 13:13:41

标签: mysql sql

SELECT Student.StudentID,
        Student.FirstName,
        Student.LastName,
        Student.EmailID,
        COUNT(SUBJECTS.SubjectID) as count from StudentMarks 
INNER JOIN Student 
        ON StudentMarks.StudentID=Student.StudentID 
INNER JOIN Subjects 
        ON StudentMarks.StudentID=Subjects.StudentID 
GROUP BY StudentMarks.StudentID 
ORDER BY count DESC LIMIT (),();

我正在通过以下计算总元组的数量:

SELECT COUNT(*) FROM (SELECT 
        Student.StudentID,
        Student.FirstName,
        Student.LastName,
        Student.EmailID,
        COUNT(SUBJECTS.SubjectID) as count from StudentMarks 
INNER JOIN Student 
        ON StudentMarks.StudentID=Student.StudentID 
INNER JOIN Subjects 
        ON StudentMarks.StudentID=Subjects.StudentID 
GROUP BY StudentMarks.StudentID 
ORDER BY count DESC) 
      as temp;

但是,我需要在第一个查询中集成此查询,并获取最后5条记录。有没有办法做到这一点? Temp给了我总共121条记录,如果我可以从中减去5并使用限制函数,它可以解决我的问题。但我不知道如何在这里集成查询?请帮忙!!

2 个答案:

答案 0 :(得分:0)

如果在DESC中不需要SORT,则可以使用以下方法:

SELECT Student.StudentID,Student.FirstName,Student.LastName,Student.EmailID,
 COUNT(SUBJECTS.SubjectID) as count from StudentMarks INNER JOIN Student ON 
StudentMarks.StudentID=Student.StudentID INNER JOIN Subjects ON 
StudentMarks.StudentID=Subjects.StudentID GROUP BY StudentMarks.StudentID ORDER BY count ASC 
LIMIT 5

针对具体要求进行编辑

SELECT * FROM 
(
     SELECT Student.StudentID,Student.FirstName,Student.LastName,Student.EmailID,
     COUNT(SUBJECTS.SubjectID) as count from StudentMarks INNER JOIN Student ON 
    StudentMarks.StudentID=Student.StudentID INNER JOIN Subjects ON 
    StudentMarks.StudentID=Subjects.StudentID GROUP BY StudentMarks.StudentID ORDER BY count ASC 
    LIMIT 5
)main ORDER BY main.count DESC

答案 1 :(得分:0)

试试这个:

select a.*,temp.C from (SELECT Student.StudentID,
        Student.FirstName,
        Student.LastName,
        Student.EmailID,
        COUNT(SUBJECTS.SubjectID) as count from StudentMarks 
INNER JOIN Student 
        ON StudentMarks.StudentID=Student.StudentID 
INNER JOIN Subjects 
        ON StudentMarks.StudentID=Subjects.StudentID 
GROUP BY StudentMarks.StudentID 
ORDER BY count DESC limit 5)a left join (SELECT StudentID,COUNT(*) as C FROM (SELECT 
        Student.StudentID,
        Student.FirstName,
        Student.LastName,
        Student.EmailID,
        COUNT(SUBJECTS.SubjectID) as count from StudentMarks 
INNER JOIN Student 
        ON StudentMarks.StudentID=Student.StudentID 
INNER JOIN Subjects 
        ON StudentMarks.StudentID=Subjects.StudentID 
GROUP BY StudentMarks.StudentID 
ORDER BY count DESC)temp on a.StudentID =temp.StudentID