如何使用SQLalchemy Core 动态连接多个表?
我有一个父表,这个表里存放了多个子表的主键。子表的数量在运行时可以是任意的。使用SQLalchemy核心,我该如何把多个子表和这个父表连接起来呢?
假设我有一些符合外键约束的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
这样一来,父表被列出了两次……
我还尝试了很多其他的组合,比如使用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
我在多个表连接方面的解决方案,受到上面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))
...
10
简单地把连接操作连在一起:
childJoins = parentTable
for child in childTables:
childJoins = childJoins.join(child)
query = sa.select(['*'], from_obj=childJoins)