是否可以根据其中一列的值,在查询执行时动态更改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;
有没有办法用单个查询执行此操作,或者我是否需要为每个学生单独执行查询(基本上按照上面的循环)?实际用例解释起来比较复杂(它与证明记录有关,需要查看哪些记录),但从概念上讲它是相同的。
答案 0 :(得分:1)
只需为a1
表使用多个别名(例如a2
和attendance
),这样就可以在子查询中引用“外部”表别名:
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;