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

Issue

I have a list of items:

list1 = ['abc', 'cde']

So, the number of elements in the list can change based on input to the function. I want to generate a query like this from the list:

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

So this query needs to be generated dynamically based on elements in the list. Because the number of LIKE commands will increase with number of elements in the list, I am unable to get it in place. The length(column)<=7 part is also dynamic but I can configure that as it is static. Can anyone help me generate the query with multiple LIKE commands based on number of list elements


Solution

You tagged this with python so I'm assuming you can use that.

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)

this returns

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


Answered By - clark-fischer
Answer Checked By - Timothy Miller (sql.easybugfix Admin)

Related Posts

Post a Comment