简体   繁体   English

SQLAlchemy Union括号问题

[英]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: 使用SQLAlchemy,我创建了两个查询对象,如下所示:

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. 但是它不起作用,因为SQLAlchemy生成查询:q1和q2不在括号内,它会产生错误。

How can I get these statements inside parenthesis for q1 q2 union to result in above expressed query? 如何在q1 q2 union的括号内获取这些语句以产生上述表达式查询?

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. .subquery()方法返回一个Alias对象 ,该对象不直接支持union_all查询。 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. 因此,我们需要构建一个select_entity_from()构造 ,而不是传入sqlalchemy.sql.expression.union_all() 函数结果,因此您仍然可以将结果映射到正确的对象。

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

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