I'm trying to do a WHERE EXISTS
clause in SQLAlchemy. The SQL looks like this:
SELECT
id, title
FROM
package AS package1
WHERE
EXISTS (
SELECT
title
FROM
package as package2
WHERE
package1.id <> package2.id AND
package1.title = package2.title
)
ORDER BY
title DESC;
Is it possible to do this in SQLAlchemy without using raw SQL? I've tried this but it doesn't seem to be returning the correct results:
t = model.Session.query(
model.Package.id,
model.Package.title
).subquery('t')
package = model.Session.query(
model.Package.title
).filter(
model.Package.id != t.c.id,
model.Package.title == t.c.title
)
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.
all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does not apply to a query that is against individual columns.
It does return an empty list.
The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name.
Use sqlalchemy.orm.aliased() and exists():
from sqlalchemy.orm import aliased
package_alias = aliased(Package)
session.query(Package.id, Package.title) \
.filter(session.query(package_alias.title) \
.filter(Package.id != package_alias.id) \
.filter(Package.title == package_alias.title) \
.exists()) \
.order_by(Package.title.desc())
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