在 python 中生成动态查询

generating dynamic query in python

我有一个包含 tablename 的列表,例如 table A,table B,table C ... 等。[=24= 的列表]s 可能会根据某些条件而改变。有时列表可能有 4 tables 或 6 tables .

tables = [table A, table B , table C, table D]

列表中 table 的架构定义相同。

我想生成如下查询。

select col A from table A 
union distinct    
select col A from table B
 union distinct 
 select col A from table C 
 union distinct  select col A
 from table D

查询的大小可能会增加或减少,具体取决于列表中的 tables

准备好查询后。它需要通过 python

在 bigquery 中执行

鉴于问题,我不确定整体设置以及需要执行此最终查询的位置。

由于问题标题中有“动态”,我提供了一个使用 f strings 的解决方案,它应该允许大多数动态插入。

这是使用 f strings 和 pandas 库进行大查询的方法。

import pandas as pd
from pandas.io import gbq

### create your final sql string to be executed to which you will append
final_sql_string = """
"""

tables = ['table_A', 'table_B', 'table_C', 'table_D']

for table in tables:

    ### if this is your last table in list no need for union
    if table == tables[-1]:

        ### build out your query via f string 
        sql_string= f"""select col_A from `your_project.your_dataset.{table}`"""

        ### join via newline to your final sql query string
        final_sql_string = "\n".join((final_sql_string, sql_string))

    ### if table is not last table then need to union
    else:
        sql_string= f"""select col_A from `your_project.your_dataset.{table}` union distinct """
        final_sql_string = "\n".join((final_sql_string, sql_string))


### optional - check what your sql looks like        
print(final_sql_string)

### submit to bq via pandas to get a pandas dataframe back
### on first try will ask to authorize against your project    
pandas_dataframe_from_sql = gbq.read_gbq(final_sql_string,
                                         project_id = 'your_project_id')

上面的打印语句示例

select col_A from `your_project.your_dataset.table_A` union distinct 
select col_A from `your_project.your_dataset.table_B` union distinct 
select col_A from `your_project.your_dataset.table_C` union distinct 
select col_A from `your_project.your_dataset.table_D`

如果您通过 google 云 SDK 执行,您也可以在其中插入此 sql。