【问题标题】:Dynamically generating where statements during runtime在运行时动态生成 where 语句
【发布时间】:2017-01-07 19:54:39
【问题描述】:

我正在使用 Sqlalchemy 来自动分析我们运行的 A/B 测试的 SQL 查询。

这是一个示例查询:

    uniques_by_day = select([
                        first_seen_byos.c.unique_id,
                        func.date_trunc('day', a_unique_users.c.ds).label('current_day'),
                        func.date_trunc('day', first_seen_byos.c.ds).label('cohort_join_day')
                        ]).\
                    select_from(joined_table).\
                    where(
                        and_(
                            a_unique_users.c.os_type == 'iphone_native_app',
                            first_seen_byos.c.ds >= '2017-01-01'
                            )
                        )

查询之间的变化是 where / and_ 语句的子句。如何编写能够使用一组动态 where 子句的一般语句?我预计这些子句将始终是一系列 AND 子句。

【问题讨论】:

  • where( 1=1 and_(...)) 有帮助吗?
  • 不确定在这种情况下我会如何使用它

标签: python sql postgresql sqlalchemy


【解决方案1】:

当我需要动态构建查询时,我通常会这样做:

query = session.query(MyTable)
if case_1:
    query = query.filter(MyTable.column_1 == 'foo')
if case_2:
    query = query.filter(MyTable.column_2 == 'bar')
query_results = query.all()

这是使用声明性基本语法,但我认为它可以理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2011-03-27
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多