SQLAlchemy - subquery in a WHERE clause

前端 未结 3 1722
天命终不由人
天命终不由人 2020-12-07 18:59

I\'ve just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts.

Boiled down to the essential elements, I have

3条回答
  •  难免孤独
    2020-12-07 19:05

    It is usually expressed similarly to the actual SQL - you create a subquery that returns single result and compare against that - however what sometimes can be real pain is if you have to use a table in the subquery that you are already querying or joining on.

    Solution is to create an aliased version of the model to reference in the subquery.

    So let's say you are already operating in a connection where you have an existing Posts model and some basic query ready - now, you'd want to query for the list of latest (single) post from each user, you'd filter the query like:

    from sqlalchemy.orm import aliased
    posts2 = aliased(Posts) # create aliased version
    
    query = query.filter(
        model.post_id
        ==
        Posts.query # create query directly from model, NOT from the aliased version!
            .with_entities(posts2.post_id) # only select column "post_id"
            .filter(
                posts2.user_id == model.user_id
            )
            .order_by(posts2.post_id.desc()) # assume higher id == newer post
            .limit(1) # we must limit to a single row so we only get 1 value
    )
    

    I've purposedly did not use the func.max because I consider that a simpler version and it's already in other answers, this example I think will be useful to people that generally find this question because they are looking for a solution how to subquery the same table.

提交回复
热议问题