Left join and nested inner join

121 views
Skip to first unread message

Michael Ekoka

unread,
Jul 3, 2023, 8:29:17 AM7/3/23
to sqlalchemy
Hi, I'm looking for the SQLAlchemy equivalent to the query

SELECT *
FROM a
LEFT OUTER JOIN (b INNER JOIN c ON b.id = c.b_id)
ON a.id = b.a_id

Related:

Table "b" and "c" are joined and filtered first, then the outer join is applied. I was able to achieve the same results using a subquery, whose fields I was subsequently able to load using `contains_eager`. FYI

subq = session.query(B).join(C).subquery(with_labels=True)
q = (session.query(A)
     .outerjoin(subq, A.id==subq.c.b_a_id)
     .options(contains_eager(A.b, alias=subq)
              .options(contains_eager(B.c, alias=subq))))
r = q.all()


I'm curious whether there's an equivalent using the above nested join syntax.

Thanks.


Mike Bayer

unread,
Jul 3, 2023, 9:49:58 AM7/3/23
to noreply-spamdigest via sqlalchemy
use the join construct directly

from sqlalchemy.orm import join


stmt = select(A).outerjoin(join(B, C), A.id == B.a_id)
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Michael Ekoka

unread,
Jul 5, 2023, 3:32:55 AM7/5/23
to sqlalchemy
Thanks, it worked.
Reply all
Reply to author
Forward
0 new messages