简体   繁体   English

SQLAlchemy子查询in子句没有连接

[英]SQLAlchemy subquery in from clause without join

i need a little help. 我需要一些帮助。 I have following query and i'm, curious about how to represent it in terms of sqlalchemy.orm. 我有以下查询,我很好奇如何用sqlalchemy.orm来表示它。 Currently i'm executing it by session.execute. 目前我正在通过session.execute执行它。 Its not critical for me, but i'm just curious. 它对我来说并不重要,但我只是好奇。 The thing that i'm actually don't know is how to put subquery in FROM clause (nested view) without doing any join. 我实际上不知道的是如何在不执行任何连接的情况下将子查询放在FROM子句(嵌套视图)中。

select g_o.group_ from (
    select  distinct regexp_split_to_table(g.group_name, E',') group_
        from (
            select array_to_string(groups, ',') group_name
            from company
            where status='active'
            and   array_to_string(groups, ',') like :term
            limit :limit
        ) g
    ) g_o
where g_o.group_ like :term
order by 1
limit :limit

I need this subquery thing because of speed issue - without limit in the most inner query function regexp_split_to_table starts to parse all data and does limit only after that. 由于速度问题,我需要这个子查询的东西 - 在大多数内部查询函数中没有限制, regexp_split_to_table开始解析所有数据并且仅在此之后进行限制。 But my table is huge and i cannot afford that. 但我的桌子很大,我付不起钱。

If something is not very clear, please, ask, i'll do my best) 如果事情不是很清楚,请问,我会尽我所能)

I presume this is PostgreSQL. 我认为这是PostgreSQL。

To create a subquery, use subquery() method. 要创建子查询,请使用subquery()方法。 The resulting object can be used as if it were Table object. 生成的对象可以像使用Table对象一样使用。 Here's how your query would look like in SQLAlchemy: 以下是SQLAlchemy中查询的外观:

subq1 = session.query(
    func.array_to_string(Company.groups, ',').label('group_name')
).filter(
    (Company.status == 'active') &
    (func.array_to_string(Company.groups, ',').like(term))
).limit(limit).subquery()

subq2 = session.query(
    func.regexp_split_to_table(subq1.c.group_name, ',')
        .distinct()
        .label('group')
).subquery()

q = session.query(subq2.c.group).\
    filter(subq2.c.group.like(term)).\
    order_by(subq2.c.group).\
    limit(limit)

However, you could avoid one subquery by using unnest function instead of converting array to string with arrayt_to_string and then splitting it with regexp_split_to_table : 然而,你可避免一个子查询使用unnest函数,而不是转换数组字符串arrayt_to_string ,然后用它分裂regexp_split_to_table

subq = session.query(
    func.unnest(Company.groups).label('group')
).filter(
    (Company.status == 'active') &
    (func.array_to_string(Company.groups, ',').like(term))
).limit(limit).subquery()

q = session.query(subq.c.group.distinct()).\
    filter(subq.c.group.like(term)).\
    order_by(subq.c.group).\
    limit(limit)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM