【问题标题】:How to check if value is in a list or if the list is empty?如何检查值是否在列表中或列表是否为空?
【发布时间】:2017-06-11 15:56:44
【问题描述】:

我正在使用psycopg2 通过 Python 3 访问 PostgreSQL 数据库,并且我正在尝试查询我想选择名称在列表中的所有用户,如果列表不是空。如果提供的列表为空,我想忽略该条件,即选择所有用户而不管他们的名字。

我已经尝试了以下三个调用:

# Using list
cursor.execute(
    "SELECT age FROM user WHERE %(names) = '{}' OR user.name IN %(names)s",
    {'names': []},
)

# Using tuple
cursor.execute(
    "SELECT age FROM user WHERE %(names) = () OR user.name IN %(names)s",
    {'names': ()},
)

# Using both list and tuple
cursor.execute(
    "SELECT age FROM user WHERE %(names_l) = '{}' OR user.name IN %(names_t)s",
    {'names_l': [], 'names_t': ()},
)

但它们都从某一点或另一点引发了无效的语法错误:

# Using list
psycopg2.ProgrammingError: syntax error at or near "'{}'"
LINE 17:         user.name IN '{}'

# Using tuple
psycopg2.ProgrammingError: syntax error at or near ")"
LINE 16:         () == ()

# Using both list and tuple
psycopg2.ProgrammingError: syntax error at or near ")"
LINE 17:         user.name IN ()

【问题讨论】:

    标签: postgresql list parameters psycopg2 where-in


    【解决方案1】:

    对于可选参数,您需要一个 SQL where 子句,例如:

    where column = :parameter or :parameter is null
    

    使用上面的参数is null时会返回所有行,否则只返回满足条件的行。

    Psycopg 将 Python list 改编为 Postgresql array。检查任何 Postgresql array 值是否等于某个值:

    where column = any (array[value1, value2])
    

    从一个空的 Python list 获取一个 Python None,它适用于 Postgresql null

    parameter = [] or None
    

    dictionary 传递给cursor.execute 方法可避免参数参数中的参数重复:

    names = ['John','Mary']
    
    query = """
        select age
        from user
        where user.name = any (%(names)s) or %(names)s is null
    """
    print (cursor.mogrify(query, {'names': names or None}).decode('utf8'))
    #cursor.execute(query, {'names': names or None})
    

    输出:

    select age
    from user
    where user.name = any (ARRAY['John', 'Mary']) or ARRAY['John', 'Mary'] is null
    

    当列表为空时:

    select age
    from user
    where user.name = any (NULL) or NULL is null
    

    http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

    【讨论】:

    • 我现在感觉很傻,没有意识到我可以使用 SQL 的 NULL,即使我知道它存在并且所有......但这很好用,感谢您的帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2014-12-29
    • 1970-01-01
    相关资源
    最近更新 更多