SQLAlchemy Union Parenthesis Issue

后端 未结 1 710
面向向阳花
面向向阳花 2020-12-31 17:48

I need to generate a query similar to the following:

(select * from ... where .. and .. order by .. limit ..)
union all
(select * from ... where .. and .. or         


        
相关标签:
1条回答
  • 2020-12-31 18:05

    You need to create subqueries, then select from those subqueries:

    from sqlalchemy import union_all
    
    q1 = Session.query(..).filter(..).filter(..).order_by(..).limit(..).subquery()
    q2 = Session.query(..).filter(..).filter(..).order_by(..).limit(..).subquery()
    q = Session.query(..).select_entity_from(union_all(q1.select(), q2.select()).order_by(..).all()
    

    The .subquery() method returns an Alias object, which does not support union_all queries directly. So instead, we need to build a select_entity_from() construct, passing in the sqlalchemy.sql.expression.union_all() function result instead, so you still get the results mapped to the correct objects.

    0 讨论(0)
提交回复
热议问题