问题描述
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