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
4

2 回答 2

10

简单地链接连接:

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

query = sa.select(['*'], from_obj=childJoins)
于 2013-01-26T20:45:46.510 回答
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))
...
于 2017-12-02T05:36:34.547 回答