I need to execute this query::
select field11, field12 from Table_1 t1 left outer join Table_2 t2 ON t2.tbl1_id = t1.tbl1_id where t2.tbl2_id is null
I had these classes in python:
class Table1(Base): .... class Table2(Base): table_id = Column( Integer, ForeignKey('Table1.id', ondelete='CASCADE'), ) ....
How do I get to the above from the below?
DEBUG) Base = declarative_base() class table_1(Base): __tablename__ = 'table_1' ID = Column(Integer) FIRST_NAME = Column(String(80),primary_key = True) LAST_NAME = Column(String(80)) class table_2(Base): __tablename__ = 'table_2' ID_1 = Column(Integer) FIRST_NAME_1 = Column(String(80),primary_key = True) LAST_NAME_1 = ...
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.
In this chapter, we will learn how to use Joins in SQLAlchemy. Effect of joining is achieved by just placing two tables in either the columns clause or the where clause of the select() construct. Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another.
q = session.query(Table1.field1, Table1.field2)\ .outerjoin(Table2)\ # use in case you have relationship defined # .outerjoin(Table2, Table1.id == Table2.table_id)\ # use if you do not have relationship defined .filter(Table2.tbl2_id == None)
should do it, assuming that field1
and field2
are from Table1
, and that you define a relationship:
class Table2(Base): # ... table1 = relationship(Table1, backref="table2s")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With