繁体   English   中英

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

[英]How to dynamically join multiple tables using SQLalchemy Core?

我有一个父表,其中包含几个子表的主键。 子表的数量在运行时可以是任意的。 使用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

只需链接联接:

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

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

我在多表联接上的解决方案,是受到上述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))
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM