我正在尝试构建一个相对复杂的查询,并希望直接操作结果的 where 子句,而不是克隆/子查询返回的查询。一个示例如下所示:
session = sessionmaker(bind=engine)()
def generate_complex_query():
return select(
columns=[location.c.id.label('id')],
from_obj=location,
whereclause=location.c.id>50
).alias('a')
query = generate_complex_query()
# based on this query, I'd like to add additional where conditions, ideally like:
# `query.where(query.c.id<100)`
# but without subquerying the original query
# this is what I found so far, which is quite verbose and it doesn't solve the subquery problem
query = select(
columns=[query.c.id],
from_obj=query,
whereclause=query.c.id<100
)
# Another option I was considering was to map the query to a class:
# class Location(object):pass
# mapper(Location, query)
# session.query(Location).filter(Location.id<100)
# which looks more elegant, but also creates a subquery
result = session.execute(query)
for r in result:
print r
这是生成的查询:
SELECT a.id
FROM (SELECT location.id AS id
FROM location
WHERE location.id > %(id_1)s) AS a
WHERE a.id < %(id_2)s
我想获得:
SELECT location.id AS id
FROM location
WHERE id > %(id_1)s and
id < %(id_2)s
有什么办法可以做到这一点?这样做的原因是我认为查询 (2) 稍微快一点(不多),并且我已经到位的映射器示例(上面的第二个示例)弄乱了标签(id
变成anon_1_id
或者a.id
如果我命名别名)。