使用sqlalchemy循环连接多个表

2024-06-01 11:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含表名和列名的字典,比如input = {'demographics':['age', 'gender'], 'automobile':['aut-01'], 'flyers':['fly-00', 'fly-01']},键是表名,值是要从该表中提取的列的列表。所有表都要通过主键id连接在一起

我创建tables_needed_to_load = input.keys()columns_needed_to_load = input.values(),然后我创建

if len(tables_needed_to_load) >= 1:
    base_table = Table(tables_needed_to_load[0], metadata, autoload = True, autoload_with = engine)
    base_col = [base_table.c[c] for c in columns_needed_to_load[0]]

if len(tables_needed_to_load) >= 2:
    for t, l in zip(tables_needed_to_load[1:], columns_needed_to_load[1:]):
        table = Table(t, metadata, autoload = True, autoload_with = engine)
        base_col += [table.c[c] for c in l]
        j = outerjoin(base_table, table, table.c.id == base_table.c.id)

s = select(base_col).select_from(j)
result = connection.execute(s)

但是这不起作用。原始SQL语句如下所示。 SELECT demographics.age, demographics.gender, automobile."aut-01", flyers."fly-01", flyers."fly-00" FROM automobile, demographics LEFT OUTER JOIN flyers ON flyers.id = demographics.id。似乎三个表都没有发生连接。只有传单和人口统计结合在一起


Tags: columnstoidinputtablesbasetableload