0

是否可以根据其中一列的值在执行查询时动态更改 where 子句?也就是说,假设(这是一个完全虚构的例子)我有一张学生表,参加过的课程,以及他们是否迟到。我想为每个学生查看自上次迟到以来上过的所有课程的列表。所以查询看起来像这样:

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

或者,把它放到更多的编程术语中,也许更清楚:

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;

有没有办法用一个查询来做到这一点,还是我需要为每个学生做一个单独的查询(基本上按照上面的循环)?实际用例解释起来更复杂(它与证明记录有关,以及需要查看哪些记录),但在概念上是相同的。

4

1 回答 1

1

只需为表使用多个别名(例如a1and a2attendance,这样您就可以在子查询中引用“外部”表别名:

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;
于 2012-06-30T19:48:43.403 回答