How to union across multiple tables in SQLAlchemy?

前端 未结 2 1639
灰色年华
灰色年华 2021-01-13 04:30

I have a few different notification tables, and I would like to perform a union across all of them to show the user all of their notifications. However, the union is not wor

相关标签:
2条回答
  • 2021-01-13 05:06

    It's certainly possible to union different tables with sqlalchemy, you just have to specify what columns you're fetching out of each table so they can be combined properly. Say you have entities A and B, do this:

    from sqlalchemy.sql.expression import label
    ...
    
    a = session.query(label('col1', A.someColumn))
    b = session.query(label('col1', B.someOtherColumn))
    both = a.union_all(b)
    

    In this case, all you'd have to be aware of is that if A.someColumn and B.someOtherColumn can't be coerced to the same type, your dbms might freak out :)

    For an example in the "real world", see line 85, 87, and 90:

    https://gerrit.wikimedia.org/r/#/c/147312/4/wikimetrics/metrics/rolling_active_editor.py

    That creates a subquery of two different tables unioned together. That subquery is then used later in a join, and its columns accessed via .c.column as usual.

    0 讨论(0)
  • 2021-01-13 05:20

    I don't think this can work with a union, even supposing the query was generated as you expect. You're querying three different object types. When the ORM gets the rows back from the database, I don't see a way for it to map rows to the right class.

    A UNION in this case doesn't make much sense since the third column has a different meaning in all three tables.

    You should do the three queries separately, unless your three notification types inherit from a common ORM-mapped class. In that case SQLAlchemy supports querying the four types all at once, although not with a UNION.

    0 讨论(0)
提交回复
热议问题