gpt4 book ai didi

python - 我如何在 sqlalchemy ORM 中表达这个查询?

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:26 25 4
gpt4 key购买 nike

这是我的 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

我有 survey_specsurvey_installation_historyusers 的 ORM 实体,并且 survey_spec.installations 是一种关系使用 survey_spec_id 作为键来 survey_installation_history

最佳答案

您有到目前为止所得到的示例输出吗?即输出:

print survey_spec.query.filter(survey_spec.survey_id==survey_id).options(
eagerload(...))

如果您只想加载实体,您可以绕过 SQL 生成并从给定的 literal 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()

关于python - 我如何在 sqlalchemy ORM 中表达这个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4228825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com