如何使用SQLAlchemy在嵌套查询中存在哪些内容?

时间:2015-12-07 17:11:33

标签: python sql sqlalchemy

我正在尝试在SQLAlchemy中执行WHERE EXISTS子句。 SQL看起来像这样:

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;

是否可以在SQLAlchemy中执行此操作而不使用原始SQL?我试过了,但它似乎没有返回正确的结果:

    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
    )

1 个答案:

答案 0 :(得分:4)

Wse sqlalchemy.orm.aliased()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())