2

比較的複雑なクエリを作成しようとしていますが、返されたクエリを複製/サブクエリせずに、結果の 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) の方がわずかに高速で (それほど多くはありません)、配置したマッパーの例 (上記の 2 番目の例) がラベルを台無しにする (エイリアスに名前を付けるとorにidなる) ためです。anon_1_ida.id

4

1 に答える 1