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

时间:2013-01-26 18:18:28

标签: python sqlalchemy

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

假设我有类sqlalchemy.schema.Table的表,并且有效的FK约束;我该如何构建这个查询?

我试过了,但是,

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 个答案:

答案 0 :(得分:5)

简单地链接连接:

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

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

答案 1 :(得分:0)

我在多桌加入的解决方案,受AudriusKaž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))
...
相关问题