1

我希望一切都好。首先,我很抱歉我的 SQL 不是很好。

我有一个如下所示的原始 SQL

select a.appointmentId, a.patientId, r.MaxTime from (
    select appointmentid, patientid, max(apptDate) as MaxTime
        from appointment 
        where facilityid=95
        group by patientid
    ) r
inner join

Appointment a on 
a.patientid = r.patientid and 
a.apptDate = r.MaxTime

我在我的代码中使用了 SQLAlchemy 的声明式风格,这就是我的查询的样子

appt_query = alchemy_session.query(Appointment.appointmentId, Appointment.patientId,          func.max(Appointment.apptDate).label('maxTime')).filter(

        Appointment.facilityId == 95,

).group_by(Appointment.patientId).subquery()


 appointments  = alchemy_session.query(Appointment.appointmentId, Appointment.patientId,    appt_query.c.maxTime).outerjoin(

            appt_query, and_(
                Appointment.patientId == appt_query.c.patientId,
                Appointment.apptDate == appt_query.c.maxTime
            )

)

但是当我这样做时

打印约会

不幸的是,它没有产生我想要的 SQL。我知道我对 SQL 的理解存在缺陷,因此任何关于此的指针都会非常有帮助。感谢您的时间和帮助。

4

1 回答 1

0

正如 sayap 所提到的,这非常接近于同一个查询。修复.outerjoin()to之后.join(),剩下的唯一事情就是提供一个Appointment别名实例,这样子查询就不会被关联。这很好地完成了sqlalchemy.orm.aliased

>>> from sqlalchemy.orm import aliased, Query
>>> appt_alias = aliased(Appointment)
>>> appt_query = Query([Appointment.appointmentId,
...                     Appointment.patientId,
...                     func.max(Appointment.apptDate).label('maxTime')]) \
...             .filter(Appointment.facilityId == 95,) \
...             .group_by(Appointment.patientId) \
...             .subquery()
>>> appointments  = Query([appt_alias.appointmentId,
...                        appt_alias.patientId,
...                        appt_query.c.maxTime]) \
...                 .join(appt_query, and_(
...                     appt_alias.patientId == appt_query.c.patientId,
...                     appt_alias.apptDate == appt_query.c.maxTime) )
>>> 
>>> print appointments
SELECT appointment_1."appointmentId" AS "appointment_1_appointmentId", appointment_1."patientId" AS "appointment_1_patientId", anon_1."maxTime" AS "anon_1_maxTime" 
FROM appointment AS appointment_1 JOIN (SELECT appointment."appointmentId" AS "appointmentId", appointment."patientId" AS "patientId", max(appointment."apptDate") AS "maxTime" 
FROM appointment 
WHERE appointment."facilityId" = :facilityId_1 GROUP BY appointment."patientId") AS anon_1 ON appointment_1."patientId" = anon_1."patientId" AND appointment_1."apptDate" = anon_1."maxTime"
于 2012-04-15T04:45:14.060 回答