将内部select的SQL查询转换为sqlalchemy

时间:2016-03-02 19:15:33

标签: sql sqlalchemy

我有以下查询来查找每条内容的最旧content_revision(content_revision.content_id):

select r1.id from content_revision r1
join (
  select r2.content_id as content_id, min(ts_created) as min_ts_created from content_revision r2
  group by r2.content_id
  order by min(ts_created) desc
) as inner_result
on r1.content_id = inner_result.content_id
and r1.ts_created = inner_result.min_ts_created limit 10;

我正在尝试将其转换为sqlalchemy(不运行普通的sql语句),但我不确定如何编写查询的“on”部分。这是我到目前为止所得到的:

db.session.query(RevisionModel.id)
.join(
  db.session.query(RevisionModel.content_id, func.min(RevisionMode.ts_created))
    .group_by(RevisionModel.content_id)
    .order_by(func.min(RevisionModel.ts_created).desc())
)
??

1 个答案:

答案 0 :(得分:1)

.join()的第二个参数是连接条件:

db.session.query(RevisionModel.id) \
          .join(subquery, and_(subquery.c.content_id == RevisionModel.content_id,
                               subquery.c.min_ts_created == RevisionModel.ts_created))

您还需要确保将您的子Query转换为带有正确标记列的select

subquery = db.session.query(RevisionModel.content_id.label("content_id"),
                            func.min(RevisionModel.ts_created).label("min_ts_created")) \
    .group_by(RevisionModel.content_id) \
    .order_by(func.min(RevisionModel.ts_created).desc()) \
    .subquery("inner_result")