Sqlalchemy in_ subquery

前端 未结 2 1204
無奈伤痛
無奈伤痛 2021-02-20 12:52

I am trying to implement a select with a nested select clause, to find parents without any children. My tables (radically simplified) are as follows:

class Pers         


        
2条回答
  •  日久生厌
    2021-02-20 13:01

    Using a subquery:

    sub_stmt = config.Session.query(ChildTable.person_id)
    stmt = config.Session.query(Person).filter(~Person.id.in_(sub_stmt))
    empty_persons = stmt.all()
    

    emits the following sql:

    SELECT person.id AS person_id, person.name AS person_name
    FROM person
    WHERE person.id NOT IN (SELECT foo.person_id AS foo_person_id
    FROM foo)
    

    Using a join:

    stmt = config.Session.query(Person).outerjoin(ChildTable).filter(ChildTable.person_id.is_(None))
    empty_persons = stmt.all()
    

    emits the following sql:

    SELECT person.id AS person_id, person.name AS person_name
    FROM person LEFT OUTER JOIN foo ON person.id = foo.person_id
    WHERE foo.person_id IS NULL
    

    I think both achieve your desired result set.

提交回复
热议问题