Phi*_*hil 9 python sqlalchemy python-2.7
我需要生成类似于以下内容的查询:
(select * from ... where .. and .. order by .. limit ..)
union all
(select * from ... where .. and .. order by .. limit ..)
order by ..
Run Code Online (Sandbox Code Playgroud)
使用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()
Run Code Online (Sandbox Code Playgroud)
但是它不起作用,因为SQLAlchemy生成查询:q1和q2不在括号内,它会产生错误.
如何在q1 q2 union的括号内获取这些语句以产生上述表达式查询?
Mar*_*ers 17
您需要创建子查询,然后从这些子查询中进行选择:
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()
Run Code Online (Sandbox Code Playgroud)
该.subquery()方法返回Alias对象,该对象不union_all直接支持查询.因此,我们需要构建一个select_entity_from()构造,而不是传递sqlalchemy.sql.expression.union_all() 函数结果,因此您仍然可以将结果映射到正确的对象.
| 归档时间: |
|
| 查看次数: |
3301 次 |
| 最近记录: |