python - 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。有没有一种方法可以根据字段的长度在循环中执行此操作,而不必像我上面所做的那样手动明确提到每个条件。
解决方案
您应该将值保留在列表或字典中,然后可以使用for
-loop 过滤空元素。
稍后您可以使用字符串函数和-loop 使用 word等for
转换col = val
和join()
连接这些元素。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
推荐阅读
- c# - 如何在 OData 中全局更改 MaxExpansionDepth 设置
- python - 在 matplotlib 中将绘图附加到 HTML 文件
- javascript - 反应:链接到另一个 html 页面上的 div
- c# - 在 EF 核心中搭建脚手架时出现 sql 连接字符串错误?
- javascript - 将 css 颜色转换为 Javascript 颜色
- python-3.x - 如何在 python 的 Flask 中创建实用程序类的通用实例?
- google-sheets - 结合 JOIN 和 ARRAYFORMULA 不起作用
- android - UnitTest 协程 Kotlin 用例 MVP
- maven - Maven ComparableVersion 包含“加载已知空值”的错误
- java - 当前运行的片段在尝试从图库中导入照片时关闭并返回之前的活动