在SQLAlchemy中加入子查询

时间:2013-08-27 19:55:25

标签: python sql sqlalchemy greatest-n-per-group

我有以下SQL查询(它是每个组中某个列中最大的一个,有3个要分组的内容):

select p1.Name, p1.nvr, p1.Arch, d1.repo, p1.Date
from Packages as p1 inner join
    Distribution as d1
    on p1.rpm_id = d1.rpm_id inner join (
        select Name, Arch, repo, max(Date) as Date
        from Packages inner join Distribution
            on Packages.rpm_id = Distribution.rpm_id
        where Name like 'p%' and repo not like '%staging'
        group by Name, Arch, repo
    ) as sq
    on p1.Name = sq.Name and p1.Arch = sq.Arch and d1.repo = sq.repo and p1.Date = sq.Date
    order by p1.nvr

我正在尝试将其转换为SQLAlchemy。这就是我到目前为止所做的:

p1 = aliased(Packages)
d1 = aliased(Distribution)
sq = session.\
        query(
            Packages.Name,
            Packages.Arch,
            Distribution.repo,
            func.max(Packages.Date).\
                                        label('Date')).\
        select_from(
            Packages).\
        join(
            Distribution).\
        filter(
            queryfilter).\
        filter(
            not_(Distribution.repo.\
                                    like('%staging'))).\
        group_by(
            Packages.Name,
            Packages.Arch,
            Distribution.repo).subquery()

result = session.\
            query(
                p1, d1.repo).\
            select_from(
                p1).\
            join(
                d1).\
            join(
                sq,
                p1.Name==sq.c.Name,
                p1.Arch==sq.c.Arch,
                d1.repo==sq.c.repo,
                p1.Date==sq.c.Date).\
            order_by(p1.nvr).all()

当我在子查询上进行连接时会出现问题。我收到一个错误,指出没有from子句加入。这很奇怪,因为我在join函数中的子查询后面指定了一个作为参数。知道我做错了什么吗?也许我需要别名并再次做一个select_from?

编辑:确切错误

Could not find a FROM clause to join from. Tried joining to SELECT "Packages"."Name", "Packages"."Arch", "Distribution".repo, max("Packages"."Date") AS "Date" FROM "Packages" JOIN "Distribution" ON "Packages".rpm_id = "Distribution".rpm_id WHERE "Packages"."Name" LIKE :Name_1 AND "Distribution".repo NOT LIKE :repo_1 GROUP BY "Packages"."Name", "Packages"."Arch", "Distribution".repo, but got: Can't find any foreign key relationships between 'Join object on %(139953254400272 Packages)s(139953254400272) and %(139953256322768 Distribution)s(139953256322768)' and '%(139953257005520 anon)s'.

它正在尝试加入,但它表示它不知道在哪里进行加入。我的语法有问题吗?我认为根据连接函数中的内容是正确的。

1 个答案:

答案 0 :(得分:12)

显然,您需要在多个连接条件周围添加and_()

join(
    sq,
    and_(p1.Name==sq.c.Name,
    p1.Arch==sq.c.Arch,
    d1.repo==sq.c.repo,
    p1.Date==sq.c.Date)).\