简体   繁体   中英

Intersect sqlalchemy query objects

I have a two sqlalchemy query objects (q1 and q2) - they both belong to the same table and I want to be able to intersect the two queries. Since my database is MySql, q1.intersect(q2) throws sql syntax error. Is there a way to perform intersect MySql queries in sqlalchemy? My research pointed at using subqueries, aliases and left joins but all these solutions are native sql queries. I am looking for a sqlalchemy syntax.

Query:

q1 = Model1().query().filter(Model1.description.ilike(%aws%)) 
q2 = Model1().query().filter(Model1.tags.ilike(%cloud%)) 

I want to return q1.intersect(q2)

Also, what I have specified here as queries is just one of the cases of a broader set. I have a function which takes in an operator (and/or) and two operands(sql alchemy query objects, q1 and q2) which can be different and complex for different function calls. In this case, I cannot do a nested filter. I need to work with just q1 and q2.

For this simple case, you could just use two filters in the same query

results = db.query(Model1).filter(
    Model1.description.ilike('%aws'), 
    Model1.tags.ilike('%cloud%')
)

This would return the same results as an intersect.

With two separate queries:

stmt = q2.subquery()
results = q1.outerjoin(stmt, Model1.id==stmt.c.id).filter(stmt.c.id != None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM