[英]How can I express this query in sqlalchemy ORM?
Here is my SQL query: 这是我的SQL查询:
select survey_spec.survey_spec_id, cr.login as created_by, installed_at, req.login as requested_by, role
from survey_spec
join (select survey_spec_id, role, max(installed_at) as installed_at from survey_installation_history group by 1, 2) latest using (survey_spec_id)
left join survey_installation_history using (survey_spec_id, role, installed_at)
left join users cr on created_by = cr.user_id
left join users req on requested_by = req.user_id
where survey_id = :survey_id
order by created_at desc, installed_at desc
I have ORM entities for survey_spec
, survey_installation_history
, and users
, and survey_spec.installations
is a relationship to survey_installation_history
using survey_spec_id
as the key. 我对ORM实体
survey_spec
, survey_installation_history
和users
,以及survey_spec.installations
是一个关系survey_installation_history
使用survey_spec_id
的关键。
Do you have the example output of what you have got so far? 您是否有到目前为止所获得的示例输出? ie the output of:
即输出:
print survey_spec.query.filter(survey_spec.survey_id==survey_id).options(
eagerload(...))
If you just want to load up your entities, you could bypass the SQL generation and load from your given literal SQL , something along the lines of: 如果您只想加载实体,则可以绕过SQL的生成,并从给定的文字SQL加载,具体方法如下:
session.query(survey_spec).from_statement("""select survey_spec.survey_spec_id, cr.login as created_by, installed_at, req.login as requested_by, role
from survey_spec
join (select survey_spec_id, role, max(installed_at) as installed_at from survey_installation_history group by 1, 2) latest using (survey_spec_id)
left join survey_installation_history using (survey_spec_id, role, installed_at)
left join users cr on created_by = cr.user_id
left join users req on requested_by = req.user_id
where survey_id = :survey_id
order by created_at desc, installed_at desc""").params(survey_id=survey_id).all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.