Sqlalchemy in_ subquery

前端 未结 2 1203
無奈伤痛
無奈伤痛 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 12:58

    Join worked for me. Thank you. In my case I was trying to find all ordered objects (Topics) which belong to a particular customer. I have 3 tables Customer, Order, Topics

    stmt = db.session.query(Topics).outerjoin(Order).\
        filter(Order.cust_id == id)
    
    topics = stmt.all()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题