【问题标题】:PyPika Create Dynamic Where StatementsPyPika 创建动态 Where 语句
【发布时间】:2020-06-22 22:01:44
【问题描述】:

我正在使用 PyPika 构建 SQL 查询。我想根据外部方(account_list)的输入动态添加“OR”子句。我没有看到任何有关如何执行此操作或是否可行的文档。

例子:

from pypika import Query, Table, Field, CustomFunction, Order, Criterion

account_list = [ '23456', '49375', '03948' ]


Query.from_(my_table).select(my_table.product_code, account, ) \
                .where( ( my_table.product_code.like('product_1%') | \
                 my_table.product_code.like('product_2%') ) )  \
                .where( Criterion.any([my_table.account == '23456', \
                 my_table.account == '49375', my_table.account == '03948']) )

无论列表中有多少,是否可以从 account_list 中填充 Criterion 值?

非常感谢您。

【问题讨论】:

    标签: python sql pypika


    【解决方案1】:

    您可以简单地在列表中预先建立标准,然后将其传递给Criterion.any

    account_list = [ '23456', '49375', '03948' ]
    account_criterions = [my_table.account == account for account in account_list] 
    
    query = (
        Query.from_(my_table)
        .select(my_table.product_code, account)
        .where(my_table.product_code.like('product_1%') | my_table.product_code.like('product_2%'))
        .where(Criterion.any(account_criterions))
    )
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      相关资源
      最近更新 更多