SQLAlchemy 中的外连接与 ORM 映射

发布于 2024-11-13 06:52:24 字数 617 浏览 4 评论 0原文

我在 SQLAlchemy 0.6.8 中使用 ORM 映射。

我有三个表(A、B 和 C),它们之间没有外键。

我正在尝试连接表 A 和 B,然后将其与 C 进行左外连接。我期待一个命名元组,其中包含字段 A、B 和 C - C 字段有时设置为 None。)

我可以执行第一个连接只需选择两个表即可轻松完成。

(session.query(A, B)
    .filter(A.some_field = B.some_other_field))

这为我提供了一个包含字段 A 和 B 的 NamedTuple。

然后我添加外连接,以使其:

(session.query(A, B)
    .filter(A.some_field==B.some_other_field))
    .outerjoin((C, A.some_field==C.some_different_field))

结果仍然只有两个表。我无法访问 C 的其他字段(即使它们存在)。

进行左外连接以访问最右侧表的字段的正确方法是什么?

如果可以的话,我宁愿不回退到基本 SQL - 我正在尝试学习利用 ORM。

I am using the ORM Mapping in SQLAlchemy 0.6.8.

I have three tables (A, B and C), with no foreign keys between them.

I am trying to join table A and B, and then left outer join that with C. I am expecting a named tuple, with fields A, B and C - with the C field sometimes set to None.)

I can do the first join easily enough by just selecting both table.

(session.query(A, B)
    .filter(A.some_field = B.some_other_field))

That gets me a NamedTuple with fields A and B.

I then add the outer join, to make it:

(session.query(A, B)
    .filter(A.some_field==B.some_other_field))
    .outerjoin((C, A.some_field==C.some_different_field))

The result still only has two tables. I can't access the other fields of C (even in the cases where they are present).

What is the correct way to do an left outer join, to get access to the fields of the right-most table??

I'd rather not fallback to the basic SQL if I could avoid it - I am trying to learn to take advantage of the ORM.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪是无色的血 2024-11-20 06:52:24

这应该有效:

(session.query(A)
    .join(B, A.some_field == B.some_other_field)
    .outerjoin(C, A.some_field == C.some_different_field)
    .add_entity(B)
    .add_entity(C))

This should work:

(session.query(A)
    .join(B, A.some_field == B.some_other_field)
    .outerjoin(C, A.some_field == C.some_different_field)
    .add_entity(B)
    .add_entity(C))
紫轩蝶泪 2024-11-20 06:52:24

对我自己的问题的初步回答:

这段代码似乎正在生成我想要的 SQL:

(session.query(A, B, C)
    .filter(A.some_field==B.some_other_field))
    .outerjoin((C, A.some_field==C.some_different_field))

请注意在原始 session.query 调用中添加了 C 参数。

这似乎并没有达到我的预期:A 与 B 结合,C 再次与 C 结合。

我还在测试。

Tentative answer to my own question:

This code appears to be generating the SQL I want:

(session.query(A, B, C)
    .filter(A.some_field==B.some_other_field))
    .outerjoin((C, A.some_field==C.some_different_field))

Note the addition of the C parameter to the original session.query call.

This does not appear to do what I thought it would do: A joined with B joined with C left joined with C again.

I am still testing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文