首页 > 解决方案 > Python - 根据列值在循环中运行 SQL

问题描述

我正在尝试构建一个基于特定条件运行的 SQL 查询(如果一列已填满,则运行查询 1,否则运行查询 2,依此类推),如下所示:

if len(col_a) > 0 and len(col_b) > 0: ## Both columns have value
    dwh_cursor.execute(f"""select * from table where col_a = '{col_a}' and col_b = '{col_b}'""")

elif len(col_a) > 0 and len(col_b) < 1: ## Only col_a has value
    dwh_cursor.execute(f"""select * from table where col_a = '{col_a}'""")

elif len(col_a) < 1 and len(col_b) > 0: ## Only col_b has value
    dwh_cursor.execute(f"""select * from table where col_b = '{col_b}'""")

我正在尝试构建类似上面的内容,但作为变量的字段数(如col_a和的字段col_b)数量为 6。有没有一种方法可以根据字段的长度在循环中执行此操作,而不必像我上面所做的那样手动明确提到每个条件。

标签: pythonsqlloops

解决方案


您应该将值保留在列表或字典中,然后可以使用for-loop 过滤空元素。

稍后您可以使用字符串函数和-loop 使用 word等for转换col = valjoin()连接这些元素。AND

where = {
    'col_a': '',   # empty so it will skip it
    'col_b': 'A',
    'col_c': '1',
}

where_filtered = {key:val for key, val in where.items() if val}

print('where filtered:', where_filtered)

where_parts = [f'{key} = {val}' for key, val in where_filtered.items()]

print('where parts:', where_parts)

where_query = ' and '.join(where_parts)

print('where query:', where_query)

query = 'SELECT * FROM table'
if where_query:
    query += ' WHERE ' + where_query
    
print('query:', query)
    

结果:

where filtered: {'col_b': 'A', 'col_c': '1'}
where parts: ['col_b = A', 'col_c = 1']
where query: col_b = A and col_c = 1
query: SELECT * FROM table WHERE col_b = A and col_c = 1

推荐阅读