【问题标题】:Passing a list of column names to a query in psycopg2将列名列表传递给 psycopg2 中的查询
【发布时间】:2016-09-28 13:56:59
【问题描述】:

我有以下疑问:

select distinct * from my_table where %s is NULL;

我希望能够向此查询传递多个列名,但我不知道每次要检查多少列是否为空。

如何使用上述查询参数技术从同一语句中进行以下查询?:

select distinct * from my_table where "col1" is NULL or "col2" is NULL;
select distinct * from my_table where "col1" is NULL or "col2" is NULL or "col3" is NULL;

我将不胜感激包括能够获得以下内容的答案,但在这种情况下没有必要:

select distinct * from my_table where "col1" is NULL;

(我正在使用 Amazon Redshift,以防消除与 postgresql 相关的可能性)

【问题讨论】:

    标签: python postgresql amazon-redshift psycopg2


    【解决方案1】:
    query = '''
        select distinct *
        from my_table
        where
            %s or
            "col1" is NULL and %s or
            "col2" is NULL and %s or
            "col3" is NULL and %s
    '''
    

    True 传递给您要评估的条件。假设您想要col1col2 中的任何一个为null 的行:

    cursor.execute(query, (False, True, True, False))
    

    如果你想要所有行不管:

    cursor.execute(query, (True, False, False, False))
    

    顺便说一句,双引号标识符是个坏主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      相关资源
      最近更新 更多