根据 Python 列表中的元素数量动态创建 Mysql 查询

Dynamically create Mysql query based on number of elements in list in Python

我有一个物品清单:

list1 = ['abc', 'cde']

因此,列表中元素的数量可以根据函数的输入而改变。 我想从列表中生成这样的查询:

SELECT  *
FROM   table
WHERE   column LIKE '%abc%' AND column LIKE '%cde%' and length(column)<=7

所以这个查询需要根据列表中的元素动态生成。因为 LIKE 命令的数量会随着列表中元素的数量而增加,所以我无法将其放置到位。 length(column)<=7 部分也是动态的,但我可以配置它,因为它是静态的。谁能帮我根据列表元素的数量使用多个 LIKE 命令生成查询

您可以将 list1 格式化为 cte,然后将 all 与子查询一起使用:

list1 = ['abc', 'cde']
query = """
  with vals(column) as (
     {}
  )
  select t1.* from table t1 where 1 = all 
    (select t1.column like concat('%', v1.column, '%') from vals v1) and length(t1.column) <= 7;
""".format('\nunion all\n'.join(f'select "{i}"' for i in list1))

你用 python 标记了它,所以我假设你可以使用它。

command = 'SELECT * FROM table WHERE'
list1 = ['abc', 'cde', 'efg']

for i in list1:
    condition = " column LIKE '%" + i + "%' AND"
    command += condition

command += " length(column)<=7"

print(command)

这个returns

SELECT * FROM table WHERE column LIKE '%abc%' AND column LIKE '%cde%' AND column LIKE '%efg%' AND length(column)<=7

list1 = ['abc', 'cde']
col_length = 7
def generate_sql_query(where_clause, col_length):
    
    return """SELECT  *
    FROM   table
    WHERE  {0}
    AND length(column)<={1}
    """.format(where_clause, col_length)
def where_clause(wherelist, column):
    res = ' 1=1 \n'
    for elem in wherelist:
        temp = "AND " + column + " LIKE '%" + elem + "%'\n"
        res += temp
    return res
res = generate_sql_query(where_clause(list1, 'colname'), col_length)
print(res)

输出


SELECT  *
    FROM   table
    WHERE   1=1 
AND colname LIKE '%abc%'
AND colname LIKE '%cde%'

    AND length(column)<=7

不知道 list1 中的元素来自何处(它们可能是由用户提供的),您可能需要关注 SQL 注入攻击。因此,您应该考虑使用准备好的语句:

list1 = ['abc', 'def']
# The prepared statement:
sql = 'select * from table where ' + ' and '.join('column like %s' for _ in list1) + ' and length(column)<=7'
# The actual arguments to the prepared statement
args = ['%' + elem + '%' for elem in list1]
# And then something like:
cursor.execute(sql, args)