join查询

lf3rwulv  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我在mysql中有一个查询:

SELECT
    O.id,
    O.label,
    A.name
FROM
    organizations O
JOIN activities_area A JOIN assoc_organization_activities S ON
    O.identifier = S.organization_id AND A.identifier = S.activities_area_id
ORDER BY
    O.label

我正在尝试用sqlalchemy:

A = aliased(model.Activities, name='A')
S = aliased(model.AssocOrganizationsActivities, name='S')
O = aliased(model.Organizations, name='O')

organizations_query = session.query(O.id, O.label, A.name) \
                             .join(A) \
                             .join(S) \
                             .filter(O.identifier == S.organization_id) \
                             .filter(A.identifier == S.activities_area_id) \
                             .order_by(O.label) \
                             .all()

但这给了我一个错误:

InvalidRequestError: Could not find a FROM clause to join from. Tried joining to <class 'model.model.Activities'>, but got: Can't find any foreign key relationships between 'organizations' and 'activities_area'.

assocorganizationsactivities表只有3个字段:id、作为外键的组织id和作为外键的活动区域id。因此,表组织和活动都由关联组织活动链接。
如何让它工作?

omhiaaxx

omhiaaxx1#

交换连接的顺序。原始sql和查询都有相同的问题,因此:

organizations_query = session.query(O.id, ...) \    
    .join(S) \
    .join(A) \
    ...

要添加的where子句

...
    .filter(O.identifier == S.organization_id) \
    .filter(A.identifier == S.activities_area_id) \
    ...

看起来您正在尝试使用pre-ansi-join语法,但与ansi-join混合使用。它们是完全多余的,因为sqlalchemy可以根据模型之间的外键关系推断连接的on子句。原始sql的破坏方式与此类似

FROM
    organizations O
JOIN activities_area A JOIN ...

在o和a之间根本没有on子句,此外,如果不首先加入关联表,也没有明显的方法来连接它们。总而言之:

organizations_query = session.query(O.id, O.label, A.name) \
    .join(S) \
    .join(A) \
    .order_by(O.label) \
    .all()

相关问题