Python 请帮助将原始sql完全转换为SQLAlchemy代码(我尝试过,但还没有实现)
我希望一切都好。首先,我很抱歉我的SQL不是很好 我有一个原始SQL,如下所示Python 请帮助将原始sql完全转换为SQLAlchemy代码(我尝试过,但还没有实现),python,sqlalchemy,Python,Sqlalchemy,我希望一切都好。首先,我很抱歉我的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
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的理解有一些失误,所以任何关于这方面的建议都会非常有用。感谢您的时间和帮助。正如sayap所提到的,这几乎是同一个问题。在您修复了.outerjoin to.join之后,剩下的唯一事情就是为约会的一个实例提供一个别名,这样子查询就不会被关联。sqlalchemy.orm.aliased很好地实现了这一点:
除了原始SQL中的内部连接与SQLAlchemy中的外部连接之外,我没有真正注意到区别。生成的SQL是什么?如果您有权访问元数据对象,MetaData.bind.echo=True将向您显示sqlalchemy正在使用的SQL。
>>> 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"