[英]Passing a list of column names to a query in psycopg2
我有以下查询:
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 相关的可能性)
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
传递给要评估的条件。 假设您想要col1
和col2
中的任何col2
为null
:
cursor.execute(query, (False, True, True, False))
如果你想要所有行,不管:
cursor.execute(query, (True, False, False, False))
顺便说一句,双引号标识符是个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.