Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a left join in SQLALchemy?

I have a SQL query which perfroms a series of left joins on a few tables:

SELECT <some attributes> FROM table1 t1 INNER JOIN table2 t2       ON attr = 1 AND attr2 = 1 LEFT JOIN table3 t3     ON t1.Code = t2.Code AND t3.Date_ = t1.Date_ LEFT JOIN tabl4 t4     ON t4.Code = t1.code AND t4.Date_ = t1.Date_ 

So far, I have:

(sa.select([idc.c.Code])             .select_from(                 t1.join(t2, and_(t1.c.attr == 1, t2.c.attr2 = 1))                 .join(t3, t3.c.Code == t1.c.Code))) 

but I can't figure out how to make the join a LEFT JOIN.

like image 773
user1742188 Avatar asked Sep 21 '16 14:09

user1742188


People also ask

How do I join a table in SQLAlchemy ORM?

I've found that the following works to join two tables: result = session. query(User, Document). select_from(join(User, Document)). filter(User.

What is left outer join?

A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.


2 Answers

The isouter=True flag will produce a LEFT OUTER JOIN which is the same as a LEFT JOIN.

With your code:

(sa.select([idc.c.Code])         .select_from(             t1.join(t2, and_(t1.c.attr == 1, t2.c.attr2 = 1))             .join(t3, t3.c.Code == t1.c.Code, isouter=True))) 

Declarative example:

session = scoped_session(sessionmaker()) session.query(Model).join(AnotherModel, AnotherModel.model_id == Model.id, isouter=True) 
like image 55
user1742188 Avatar answered Oct 04 '22 17:10

user1742188


Here is how to use isouter:

select_from(db.join(Table1, Table2, isouter=True).join(Table3, isouter=True))  
like image 43
melchoir55 Avatar answered Oct 04 '22 17:10

melchoir55