Sqlalchemy - grouping elements and iterating through captions

Consider a table like this:

| Name       | Version | Other |
| ---------------------|-------|
| Foo        | 1       | 'a'   |
| Foo        | 2       | 'b'   |
| Bar        | 5       | 'c'   |
| Baz        | 3       | 'd'   |
| Baz        | 4       | 'e'   |
| Baz        | 5       | 'f'   |
--------------------------------

I would like to write a query statement sqlalchemy to enumerate all the elements (as the object mapper, and not only the Name column) with a maximum version: Foo-2-b, Bar-5-c, Baz-5-f. I understand that I would have to use a method group_by, but beyond that, I am puzzled by how to retrieve sub-lists (and then find the max element). The SQLAlchemy documentation does not seem to be very clear.

There are many other columns in the real scenario (for example, โ€œOtherโ€), so I need the actual row object (collation class) to be returned, and not just the value โ€œNameโ€.

+3
2

, :

max_versions = session.query(Cls.name, func.max(Cls.version).label('max_version'))\
                      .group_by(Cls.name).subquery()
objs = session.query(Cls).join((max_versions,
           and_(Cls.name == max_versions.c.name,
                Cls.version == max_versions.c.max_version)
       )).all()

- :

SELECT tbl.id AS tbl_id, tbl.name AS tbl_name, tbl.version AS tbl_version
FROM tbl JOIN (SELECT tbl.name AS name, max(tbl.version) AS max_version
FROM tbl GROUP BY tbl.name) AS anon_1 ON tbl.name = anon_1.name AND tbl.version = anon_1.max_version

, , .

+6

SQL engine.execute:

select
    t1.*
from
    table t1
    inner join 
        (select
            Name,
            max(version) as Version
         from
            table
         group by
            name) s on
        s.name = t1.name
        and s.version = t1.version
-2

Source: https://habr.com/ru/post/1715194/


All Articles