Postgresql根据列值在哪里不同?
在根据其中一列的值执行查询时,是否可以动态更改where子句?也就是说,假设(这是一个完全虚构的例子),我有一张学生表,有参加的课程,如果他们迟到了。我想为每个学生看一份自上次迟到以来他们参加的所有课程的清单。因此,查询将如下所示:Postgresql根据列值在哪里不同?,postgresql,Postgresql,在根据其中一列的值执行查询时,是否可以动态更改where子句?也就是说,假设(这是一个完全虚构的例子),我有一张学生表,有参加的课程,如果他们迟到了。我想为每个学生看一份自上次迟到以来他们参加的所有课程的清单。因此,查询将如下所示: SELECT student, class, classdate FROM attendance WHERE classdate>(<<SOME QUERY that selects the most recent tardy for each s
SELECT student, class, classdate
FROM attendance
WHERE classdate>(<<SOME QUERY that selects the most recent tardy for each student>>)
ORDER BY student,classdate;
有没有办法通过一个查询来实现这一点,或者我需要为每个学生单独查询(基本上按照上面的循环)?实际用例解释起来更复杂(它与证明记录有关,需要查看哪些记录),但概念上是一样的。只需为考勤表使用多个别名(例如a1
和a2
),因此您可以在子查询中引用“外部”表别名:
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;
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;