Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Union Parenthesis Issue

I need to generate a query similar to the following:

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

Using SQLAlchemy, I create two query objects as in:

q1 = Session.query(..).filter(..).filter(..).order_by(..).limit(..)
q2 = Session.query(..).filter(..).filter(..).order_by(..).limit(..)
q = q1.union_all(q2).order_by(..).all()

However it won't work because SQLAlchemy generates queries: q1 and q2 are not within parenthesis and it creates an error.

How can I get these statements inside parenthesis for q1 q2 union to result in above expressed query?

like image 216
Phil Avatar asked Feb 03 '13 13:02

Phil


1 Answers

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.

like image 199
Martijn Pieters Avatar answered Sep 24 '22 13:09

Martijn Pieters