简体   繁体   中英

Multiple having statements in a SQLAlchemy query

What is the order of operations in SQLAlechemy? An ideal answer will provide a set of generally applicable rules rather than a solution in the context of a specific example.

The motivation for this question is as follows. I am building a dataset from multiple tables within a SQLite3 database. My query is something like the following:

query = session.query( Customer, Application, Income, Spending ).\
join(
    <USER-APPLICATION JOIN>
).\
join(
    <USER-INCOME JOIN>
).\
join(
    <USER-SPENDING JOIN>
).\
group_by(
    User.id,
    Application.date,
)

Now, I don't want to pull everything from these tables, so I put some filters on the query. For example:

query = query.\
filter( 
    Income.date <= Application.date
).\
having(
    or_(
        and_(
            func.max(Spending.date) <= Application.date,
            Spending.date == func.max(Spending.date)
        ),
        and_(
            func.max(Spending.date) > Application.date,
            Spending.date < Application.date
        ),
        and_(
            func.min(Spending.date) > Application.date,
            Spending.date == func.min(Spending.date)
        )
    )
).\
having(
    Spending.date == func.max(Spending.date),
    Income.date == func.max(Income.date)
)

However, the having statements are dependent upon one-another, and the code above will do what I want if and only if the first having statement is applied before the second.

So is this code behaving in the way I want? Also, does this behavior depend on which database I use (I may want to upgrade databases in the future)?

In the case of:

query.filter(...).having(...)

...anything in the filter() becomes part of a WHERE clause, and content in the having() becomes part of the HAVING clause.

The WHERE clause applies to rows pre-grouping, and the HAVING clause applies to groups. As such, the HAVING clause will implicitly be scoped to rows which passed the WHERE clause.

Thus, your code will behave appropriately as-written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM