SQLAlchemy - subquery in a WHERE clause

前端 未结 3 1721
天命终不由人
天命终不由人 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:21

    the previous answer works, but also the exact sql you asked for is written much as the actual statement:

    print s.query(User, Posts).\
        outerjoin(Posts.user).\
        filter(Posts.post_time==\
            s.query(
                func.max(Posts.post_time)
            ).
            filter(Posts.user_id==User.user_id).
            correlate(User).
            as_scalar()
        )
    

    I guess the "concept" that isn't necessarily apparent is that as_scalar() is currently needed to establish a subquery as a "scalar" (it should probably assume that from the context against ==).

    Edit: Confirmed, that's buggy behavior, completed ticket #2190. In the current tip or release 0.7.2, the as_scalar() is called automatically and the above query can be:

    print s.query(User, Posts).\
        outerjoin(Posts.user).\
        filter(Posts.post_time==\
            s.query(
                func.max(Posts.post_time)
            ).
            filter(Posts.user_id==User.user_id).
            correlate(User)
        )
    

提交回复
热议问题