使用 SQLAlchemy 生成带有子查询的 sql 作为选择语句中的列 [英] Generate sql with subquery as a column in select statement using SQLAlchemy

查看:26
本文介绍了使用 SQLAlchemy 生成带有子查询的 sql 作为选择语句中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 SQLAlchemy 生成一个带有自定义列的查询,该列是与当前行相关的子查询:

Is there a way to make SQLAlchemy generate a query with a custom column that is a subquery that correlates with current row:

SELECT
 tab1.id,
 tab1.col1, 
 ...,
 (
     SELECT count(1) FROM tab2 
     WHERE tab2.tab1_id = tab1.id
     GROUP BY tab2.col1
 ) as cnt
FROM tab1
WHERE ...
LIMIT 100

使用 ORM API?

using the ORM API?

session.query(Tab1, ?(subquery for additional column)?).filter(...).limit(100)

我使用的是 PostgreSQL 9.3 和旧版本的 SQLAlchemy 0.9.8

I'm using PostgreSQL 9.3 and old version of SQLAlchemy 0.9.8

推荐答案

如果你经常需要这个,和/或计数是你的 Tab1 模型的一个组成部分,你应该使用混合属性如另一个答案中所述.另一方面,如果您只需要单个查询,那么您可以使用 Query.label()Query.as_scalar():

If you need this often, and/or the count is an integral part of your Tab1 model, you should use a hybrid property such as described in the other answer. If on the other hand you need this just for a single query, then you could just create the scalar subquery using Query.label(), or Query.as_scalar():

count_stmt = session.query(func.count(1)).
    filter(Tab2.tab1_id == Tab1.id).
    group_by(Tab2.col1).
    label('cnt')

session.query(Tab1, count_stmt).filter(...).limit(100)

子查询将自动关联它可以来自封闭查询.

The subquery will automatically correlate what it can from the enclosing query.

这篇关于使用 SQLAlchemy 生成带有子查询的 sql 作为选择语句中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆