SQLAlchemy 中的外连接与 ORM 映射
我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该有效:
This should work:
对我自己的问题的初步回答:
这段代码似乎正在生成我想要的 SQL:
请注意在原始
session.query
调用中添加了 C 参数。这似乎并没有达到我的预期:A 与 B 结合,C 再次与 C 结合。
我还在测试。
Tentative answer to my own question:
This code appears to be generating the SQL I want:
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.