Joining multiple tables

11 views
Skip to first unread message

Vetle

unread,
Aug 16, 2007, 5:45:02 PM8/16/07
to sqlalchemy
Hi,

I'm reading the documentation on SQL Alchemy, but perhaps I'm missing
something here ... I need to join multiple tables, table1 with table2
and table1 again.

So, in SQL, I'd do something like:

select * from t1 join t2 on t1.b = t2.c join t1 t3 on t1.a = t3.a;

Yeah, it doesn't make much sense, but it's an example. Any ideas on
how I'd do that in SA? I'm having trouble figuring it out. :)

Michael Bayer

unread,
Aug 16, 2007, 11:37:42 PM8/16/07
to sqlalchemy
hi Vetle -

the Table object supports a join() method, which can be called in a
chain, i.e.

table1.join(table2).join(table3)...


if you need to specify the "ON" part of the join, its the second
argument to join() (below illustrated with two joins back to table1):

table1.join(table2, table1.c.id==table2.c.someid).join(table3,
table1.c.id==table3.c.id)


hope this helps...

Vetle Roeim

unread,
Aug 17, 2007, 4:26:15 PM8/17/07
to sqlal...@googlegroups.com

Yes thanks, it helped a little bit. I realized I could to this inside
from_obj = [ ... ]. That, in addition to using table aliases.

I ended up with something like:
t1_2 = t1.alias('t1_2')
select([t1, t1.c.a .... ],
from_obj = [t1.join(t1_2, t1.c.a = t1_2.c.b).join(.....)]

It was kinda complicated, and the schema could have been designed a
little differently, but I got it working at last. ;)

--
Vetle Roeim

Reply all
Reply to author
Forward
0 new messages