如何使用SQLalchemy Core动态地连接多个表?

4

我有一个父表,其中包含多个子表的主键。子表的数量可以在运行时任意。使用SQLalchemy核心,如何将多个子表连接到此父表?

假设我有一些具有有效FK约束的类Sqlalchemy.schema.Table的表;如何构造此查询?

我尝试过例如:

childJoins= [sa.join(parentTable,childTables[0]),sa.join(parentTable,childTables[1])]
# childTables is a list() of Table objects who are guaranteed linked by pk 

qry = sa.select(["*"],from_obj=childJoins)

给出了以下结果:

SELECT * 
FROM 
parentTable JOIN child1 ON child1.P_id = parentTable.C1_Id, 
parentTable JOIN child2  ON child2.P__id = parentTable.C2_Id

所以parentTable出现了两次...

尝试使用join()等多种变化,查看文档,但我仍然无法得到我想要的结果;

SELECT *
FROM parentTable
JOIN child1 ON parentTable.C1_Id=child1.P_Id
JOIN child2 ON parentTable.C2_Id=child2.P_Id 
...
JOIN childN ON parentTable.CN_Id=childN.P_Id
2个回答

10

只需简单地链接这些连接:

childJoins = parentTable
for child in childTables:
    childJoins = childJoins.join(child)

query = sa.select(['*'], from_obj=childJoins)

0

我的多表连接解决方案,受到上面Audrius Kažukauskas的解决方案的启发,使用SQLAlchemy核心:

from sqlalchemy.sql.expression import Select, ColumnClause

select = Select(for_update=for_update)
if self.columns:              # a list of ColumnClause objects
    for c in self.columns:
       select.append_column(c)

# table:  sqlalchemy Table type, the primary table to join to
for (join_type,left,right,left_col,right_col) in self.joins:
    isouter = join_type in ('left', 'left_outer', 'outer')
    onclause = (left.left_column == right.right_column)
    # chain the join tables
    table = table.join(right, onclause=onclause, isouter=isouter)

# if no joins, 'select .. from table where ..'
# if has joins, 'select .. from table join .. on .. join .. on .. where ..
select.append_from(table)

if self.where_clauses:
    select.append_whereclause(and_(*self.where_clauses))
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接