SqlAlchemy: filter to match all instead of any values in list?

前端 未结 3 501
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 06:58

I want to query a junction table for the value of column aID that matches all values of a list of ids ids=[3,5] in column bID.

相关标签:
3条回答
  • 2020-12-19 07:40

    You are looking for a query that works on sets of rows. I think a group by with having clause is the best approach:

    select aid
    from jt
    where bid in (<your list>)
    group by aid
    having count(distinct bid) = 2
    

    If you can put the ids that you desire in a table, you can do the following more generic approach:

    select aid
    from jt join
         bids
         on jf.bid = bids.bid
    group by aid
    having count(distinct jt.bid) = (select count(*) from bids)
    
    0 讨论(0)
  • 2020-12-19 07:42

    Try:

        session.query(JT.aID).filter(not_(JT.bID.in_(ids))).all()
    
    0 讨论(0)
  • 2020-12-19 07:53

    Based on @Gordon Linoff answer and with two tables A and B where A has a relation one- to-many towards B called A.bs the SqlAlchemy equivalent would be:

    from sqlalchemy import func  
    session.query(A).join(B).filter(B.id.in_(<your_list>)).group_by(A.id).having(func.count(A.bs) == len(<your_list>)).all()
    
    0 讨论(0)
提交回复
热议问题