how do i convert the following mysql query to sqlalchemy?
SELECT * FROM `table_a` ta, `table_b` tb where 1 AND ta.id = tb.id AND ta.id not in (select id from `table_c`)
so far i have this for sqlalchemy:
query = session.query(table_a, table_b) query = query.filter(table_a.id == table_b.id)
method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.
All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.
The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.
The ORM internals describe the not_in()
operator (previously notin_()
), so you can say:
query = query.filter(table_a.id.not_in(subquery)) # ^^^^^^
From the docs:
inherited from the
ColumnOperators.not_in()
method of ColumnOperatorsimplement the NOT IN operator.
This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).
Note that version 1.4 states:
The
not_in()
operator is renamed fromnotin_()
in previous releases. The previous name remains available for backwards compatibility.
So you may find notin_()
in some cases.
Try this:
subquery = session.query(table_c.id) query = query.filter(~table_a.id.in_(subquery))
Note: table_a
, table_b
and table_c
should be mapped classes, not Table
instances.
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