[英]Passing a list of column names to a query in psycopg2
I have the following query:我有以下查询:
select distinct * from my_table where %s is NULL;
I would like to be able to pass in more than one column name to this query, but I do not know how many columns I will want to be checking for nulls every time.我希望能够向此查询传递多个列名,但我不知道每次要检查多少列是否为空值。
How can I use query parameter techniques like the above to make both the below queries from the same statement?:如何使用上述查询参数技术从同一语句中进行以下两个查询?:
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;
I would appreciate an answer that includes being able to get the below as well, but it is not necessary in this case:我希望得到一个包括能够获得以下内容的答案,但在这种情况下没有必要:
select distinct * from my_table where "col1" is NULL;
(I am using Amazon Redshift, in case that removes an postgresql-related possibilities) (我正在使用 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
'''
Pass True
to the conditions which you want to be evaluated.将
True
传递给要评估的条件。 Say you want rows where any of col1
and col2
are null
:假设您想要
col1
和col2
中的任何col2
为null
:
cursor.execute(query, (False, True, True, False))
If you want all rows regardless:如果你想要所有行,不管:
cursor.execute(query, (True, False, False, False))
BTW double quoting identifiers is a bad idea.顺便说一句,双引号标识符是个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.