16

我有以下 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 子句。这很奇怪,因为我在连接函数中的子查询之后指定一个作为参数。知道我做错了什么吗?也许我需要别名并再次执行 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'.

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

4

1 回答 1

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)).\
于 2013-08-29T18:55:56.600 回答