使用多个列名的 SQLAlchemy 连接语法 [英] SQLAlchemy join syntax using multiple column names
问题描述
这是我要执行的以下 sql 查询,并且在命令行上完美运行:
This is the following sql query I want to execute and works perfectly on the command line:
select * from table1 join table2 using (col1, col2)
我无法弄清楚如何使用 SQLAlchemy 执行此操作,任何帮助将不胜感激.
I am cannot figure out how to make this execute using SQLAlchemy and any help would be appreciated.
表之间没有外键.表格行只能通过多列中匹配的值配对.
There are no foreign keys between the tables. The table rows can only be paired up by values matching in multiple columns.
谢谢!
推荐答案
考虑Entity1映射到table1,Entity2映射到table2:
Considering Entity1 maps to table1, and Entity2 maps to table2:
rows = session
.query(Entity1, Entity2)
.join(Entity2, (Entity1.col1==Entity2.col1) & (Entity1.col2==Entity2.col2))
.all()
rows
将是一个元组列表,其中 rows[][0]
是 Entity1
和 rows[][1]
是 Entity2
.您可以使用 .join()
然后用第二个参数指定连接条件.如果省略连接条件,则 .query()
方法单独生成 table1 和 table2 之间的交叉连接.
rows
will be a list of tuples where rows[][0]
is Entity1
and rows[][1]
is Entity2
.
You can use .join()
and then specify the join condition with the second param. If you omit the join condition, then the .query()
method alone generates a cross join between table1 and table2.
这篇关于使用多个列名的 SQLAlchemy 连接语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!