Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to dynamically change the where clause as a query executes based on the value of one of the columns? That is, lets say (and this is a completely made up example) I have a table of students, classes attended, and if they were tardy. I want to see for each student a list of all classes they have attended since the last time they were tardy. So the query would look something like this:

SELECT student, class, classdate
FROM attendance
WHERE classdate>(<<SOME QUERY that selects the most recent tardy for each student>>)
ORDER BY student,classdate;

or, to put it into more programing terminology, to perhaps make it clearer:

for studentName in (SELECT distinct(student) FROM attendance):
    SELECT student, class, classdate
    FROM attendance
    WHERE classdate>(SELECT classdate 
                     FROM attendance 
                     WHERE tardy=true AND student=studentName
                     ORDER BY classdate DESC
                     LIMIT 1)
    ORDER BY classdate;

Is there any way to do this with a single query, or do I need to do a separate query for each student (essentially as per the loop above)? The actual use case is more complicated to explain (it has to do with certifying records, and which ones need to be looked at) but conceptually it is the same.

share|improve this question

1 Answer 1

Just use multiple aliases (e.g. a1 and a2) for the attendance table, so you can refer to the "outer" table alias in the subquery:

SELECT student, class, classdate
FROM attendance a1
WHERE classdate>(SELECT classdate 
                 FROM attendance a2
                 WHERE tardy=true AND a2.student=a1.student
                 ORDER BY classdate DESC
                 LIMIT 1)
ORDER BY classdate;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.