Python psycopg2 dynamic where 子句,带有基于条件的可选 AND


这可能

不是一个新问题,但在谷歌搜索和挖掘SO一段时间后,我无法找到一个像样的解决方案。 我想根据是否设置变量将条件 AND 添加到我的 WHERE 子句中。

我可以将三元放入字符串格式,但这似乎不是一个好的解决方案。

def run_query(start_date, end_date, value):
    query = """
    SELECT * FROM table WHERE value = %(value)s {date_clause}""".format(date_clause = "AND start_date >= %(start_date)s AND end_date <= %(end_date)s" if start_date is not None and end_date is not Null else "")
cursor.execute(query, {"start_date": None, "end_date": None, "value": value})

您可以使用 Postgres 函数COALESCE()

query = """
SELECT * 
FROM my_table 
WHERE column = %(value)s 
AND otherColumn = COALESCE(%(otherValue)s, '')
"""

otherValue为 None 时,将转换为 Postgres NULL并返回COALESCE()空字符串。

最新更新