【问题标题】:Python - Cursor - Multiple filters from listsPython - 光标 - 列表中的多个过滤器
【发布时间】:2021-03-04 15:35:32
【问题描述】:

我想运行一个查询,根据两个列表中的值过滤两列。

基本上,我想模拟两个这样的过滤器:

SELECT *
FROM my_table
WHERE customers in ("John","Peter") AND customers_numbers IN ('1','2')

但是来自customers 和customers_number 的值在两个列表中。为了尝试这个,我正在编写以下代码:

list1 = ["John","Peter"]
list2 = [1,2]
query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % ','.join(['?'] * len(list1)) % ','.join(['?'] * len(list2))
cursor.execute(query_sql, list1,list2)

但我收到以下错误:

    query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % ','.join(['?'] * len(list1)) % ','.join(['?'] * len(list2))
TypeError: not enough arguments for format string

如何使用 python 进行上述查询?

谢谢!

【问题讨论】:

    标签: python sql list filter cursor


    【解决方案1】:

    您的查询中有错误,两个词之间有一个额外的%,而不是逗号。此外,当您使用包含多个术语的% 格式时,您需要将整个变量部分放在括号中的% 之后:

    query_sql = "DELETE FROM vw_bill_details WHERE customers in (%s) and customers_numbers in (%s)" % (','.join(['?'] * len(list1)), ','.join(['?'] * len(list2)))
    

    改进:

    1. 考虑将查询写入文档字符串,以便更容易阅读、编写和调试:

      query_sql = """DELETE FROM vw_bill_details
      WHERE customers in (%s)
      and customers_numbers in (%s)""" % (
      ','.join(['?'] * len(list1)), ','.join(['?'] * len(list2)))
      
    2. str.join() 适用于任何可迭代对象,包括字符串,因此 ','.join(['?'] * len(list1)) 部分可以写为 ','.join('?' * len(list1)) - ? 标记是单个字符串而不是具有单个元素的列表。

    3. 有可能匹配错误的记录:WHERE customers in ("John","Peter") AND customers_numbers IN ('1','2') 不关心/检查“John”的 cust_number 1 或 2。因此它可以匹配 John-2 和 Peter-1,而不是您'打算 John-1 和 Peter-2。

      可以在此处查看不匹配的示例:http://sqlfiddle.com/#!9/caa7f3/2

      您可以通过指定匹配的名称和号码来避免这种不匹配:

      WHERE (customers = 'John' AND customers_numbers = '1')
         OR (customers = 'Peter' AND customers_numbers = '2')
      

      也可以写成一对:

      WHERE (customers, customers_numbers) = ('John', 1)
      

      您可以通过以下方式将其扩展为多个选项:

      WHERE (customers, customers_numbers) IN (('John', 1), ('Peter', 2))
      

      使用?s 比上面的扩展AND/OR 版本更容易参数化。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 2018-01-25
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多