Python SQL格式化——根据条件省略一个where子句

问题描述

我需要根据条件写一个 sql 问题: 在条件 1 中:

SELECT
    *
FROM
    table_1
WHERE
    col_1 IS NULL
    AND col_2 IS NOT NULL

并且在条件 2 中:

SELECT
    *
FROM
    table_1
WHERE
    col_1 IS NULL

我如何才能在 Python 中轻松实现这一目标?我知道我以后可以做过滤器,但效率并不高。

解决方法

在许多工具中使用的解决方案:使用虚拟的 TRUE WHERE 子句进行初始查询,然后根据条件可以连接这样的附加过滤器(简化代码):

query = 'select * from table where 1 = 1' # WHERE with dummy TRUE condition
                                          # it can be WHERE TRUE

condition1 = True; # if both conditions are False,query will be without filters
condition2 = True;

filter1='Col1 is not null'
filter2='Col2 is not null'

if condition1:
    query = query+' and '+ filter1

if condition2:
    query = query+' and '+ filter2

print(query)

结果:

select * from table where 1 = 1 and Col1 is not null and Col2 is not null

使用 pypika 的更优雅的解决方案 - python 查询构建器。您可以构建整个查询,包括表、字段、过滤器和连接的位置:

from pypika import Query,Table,Field

table = Table('table')

q = Query.from_(table).select(Field('col1'),Field('col2'))                                          

condition1 = True;
condition2 = True;


if condition1:
    q = q.where(
    table.col1.notnull()
)

if condition2:
    q = q.where(
    table.col2.notnull()
)

print(q)

结果:

SELECT "col1","col2" FROM "table" WHERE NOT "col1" IS NULL AND NOT "col2" IS NULL

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...