mardi 23 février 2016

Applying an SQL column membership test for a variable number of patterns?

I have a text input field on a webform that will take either a single string, or a comma-separated list of strings, the query an SQLite database. I'll read in a a single Python string in either case, then place each into a list:

all_jobs = [job.strip() for job in job_title_input.split(',')]

There will likely be no more than 3 comma-separated values ever, and in the vast majority of cases there will only be 1.

Rather than hardcode something like:

if len(all_jobs) == 1:
   cursor.execute("""SELECT * FROM mytable WHERE title LIKE '%?%""", (all_jobs[0]))
elif len(all_jobs) == 2:
   cursor.execute("""SELECT * FROM mytable WHERE title LIKE '%?%' OR LIKE '%?%'""", (all_jobs[0], all_jobs[1]))
else:
    #etc

Does SQL/SQLite allow me to make this more efficient, perhaps with its own version of Python's in membership test? I am imagining a conditional expression or another list comprehension, but can't get to formulating it, as my SQL knowledge is minimal.

Aucun commentaire:

Enregistrer un commentaire