【问题标题】:Python SQL formatting -- omitting one where clause based on conditionsPython SQL 格式化——根据条件省略一个 where 子句
【发布时间】:2021-04-30 05:41:23
【问题描述】:

我需要根据条件编写一个 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 中轻松实现这一点?我知道我可以稍后再做过滤器,但这并不是应有的高效。

【问题讨论】:

    标签: python-3.x presto trino


    【解决方案1】:

    许多工具中使用的解决方案:使用虚拟 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2019-11-16
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多