编写 OR SQL 条件以从 Snowflake 中提取信息模式数据的 Pythonic 方式

Pythonic way to write OR SQL condition to extract information schema data from Snowflake

我正在使用 python 连接到 Snowflake(代码下方)。如您所见,我正在尝试获取行计数,日期 table 是根据 SNOWFLAKE_SAMPLE_DATA 数据库中存在的信息模式创建和更改的模式 'TPCDS_SF100TCL'。我的问题不是为每个 table(在下面的示例中:CUSTOMER,CALL_CENTER,CUSTOMER_ADDRESS)写“或”条件,而是想知道我是否可以在某处提供一个列表并遍历该列表以获得“或”条件。我不确定这是否可能?如果是请建议代码和解释。

提前感谢您的时间和建议!

Python代码

    import pandas as pd
    import snowflake.connector
    
    conn = snowflake.connector.connect(
                user="MY_USER",
                password="MY_PSWD",
                account="MY_ACCOUNT",
                warehouse="COMPUTE_WH",
                database="SNOWFLAKE_SAMPLE_DATA",
                schema="INFORMATION_SCHEMA",
                role="SYSADMIN"
                )
    
    cur = conn.cursor()
    
    try:
        cur.execute("SELECT TABLE_NAME,ROW_COUNT,CREATED,LAST_ALTERED  FROM TABLES WHERE TABLE_TYPE='BASE TABLE' 
AND TABLE_SCHEMA='TPCDS_SF100TCL' AND TABLE_NAME='CUSTOMER' OR TABLE_NAME='CALL_CENTER' 
OR TABLE_NAME='CUSTOMER_ADDRESS'")
        df = cur.fetch_pandas_all()
    finally:
        cur.close()
    conn.close()

BeRT2me 建议后的代码[更新:SO 用户提供的两种方法都有效。请参阅下面他建议的代码]

cur = conn.cursor()


tables = ['CUSTOMER', 'CALL_CENTER', 'CUSTOMER_ADDRESS']
try:

    cur.execute(f"""SELECT TABLE_NAME, ROW_COUNT, CREATED, LAST_ALTERED FROM TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='TPCDS_SF100TCL' AND TABLE_NAME IN ({','.join(tables)})""")
    df = cur.fetch_pandas_all()
finally:
    cur.close()
conn.close()

如果仅仅简化查询就足够了,您可以从:

开始
cur.execute(
    """
    SELECT TABLE_NAME, ROW_COUNT, CREATED, LAST_ALTERED 
    FROM TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_SCHEMA='TPCDS_SF100TCL' 
    AND TABLE_NAME IN ('CUSTOMER', 'CALL_CENTER', 'CUSTOMER_ADDRESS')
    """
)

如果你想要一种注入列表的 pythonic 方式,这应该可行:

tables = ['CUSTOMER', 'CALL_CENTER', 'CUSTOMER_ADDRESS']

cur.execute(
    f"""
    SELECT TABLE_NAME, ROW_COUNT, CREATED, LAST_ALTERED 
    FROM TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_SCHEMA='TPCDS_SF100TCL' 
    AND TABLE_NAME IN ({','.join("'" + x + "'" for x in tables)})
    """
)