python - SQLAlchemy Writing Nested Query -
i have 2 tables:
table id | values
and
table b id | foreign key | datestamp | val2
given list of id
s a
, how joined result of a
, b
rows b
have earliest datestamp
each matched a
.
for example table b have:
1 | 2 | 1/10/2015 1 | 2 | 1/2/2015 1 | 2 | 1/3/2015
i interested in row
id_a | id_b | 1/2/2015 | values | val2
to understanding in sql, can like
where timestamp = (select min(timestamp) b.x x.id = b.id)
however, how nest select inside sqlalchemy query?
for example, believe can't use
.filter(b.timestamp == (query(func.min(b.timestamp)).filter(a.id == b.foreign_key_to_a)))
actually, can use:
b2 = aliased(b, name='b2') s = session.query(func.min(b2.datestamp)).filter(b2.a_id == a.id) q = (session .query(a.id, b.id, b.datestamp, a.values, b.val2) .join(b) .filter(b.datestamp == s) )
Comments
Post a Comment