在SQL中使用带有IN语法的通配符和python

时间:2016-01-06 12:20:05

标签: python sql

我想使用通配符来检索包含所有或部分可能值的列表中的订单值的客户:

sql="SELECT order from `customers` WHERE UPPER(order) IN  (%s)"
in_p=', '.join(map(lambda x: '%s',orders))
sql = sql % in_p
cur.execute(sql,orders)

订单是订单的可能值/状态列表。此查询给出了确切的值。

示例:在customers表中,订单可能具有状态值"处理","处理"但是可能的值列表只包含" processing"我想要检索所有订单。

我希望自己清楚明白。提前感谢你

2 个答案:

答案 0 :(得分:0)

您需要LIKE SQL运算符:

where = " OR ".join(["order LIKE %s"]*len(orders))
sql = "SELECT order from `customers` WHERE " + where
cur.execute(sql, ["%{}%".format(o) for o in orders])

答案 1 :(得分:0)

好主意 - 我认为他们可以帮到你

orders=['a','b','c']
sql="SELECT order from `customers` WHERE UPPER(order) IN  (%s)"
in_p=', '.join(map(lambda x: str.format('\'{}\'',x),orders))
sql_command = sql % in_p

sql_command

SELECT order from `customers` WHERE UPPER(order) IN  ('a', 'b', 'c')