Home > Net >  Query where column match one or all, according to an argument
Query where column match one or all, according to an argument

Time:02-07

Sorry if this is basic. I have a function that get as an argument one of these 2 :

subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these

So in my function I need to query according to subjects argument

def function (subjects):
    
    query = ('''
                SELECT date_num, subject, in_col
                FROM base
                WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?

        ''').format(subjects=subjects)

so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?

Could I send * instead ? like subjects[*] ?

(I do turn the ['a','b'] into ('a','b') in my code )

CodePudding user response:

subjects = ['ALL']
# subjects = ['A', 'B']
where_clause = f"WHERE subject in {tuple(subjects)}" if subjects[0] != "ALL" else ""

query = f'''SELECT date_num, subject, in_col FROM base {where_clause}'''

Try uncommenting the second line to check how the query modifies

CodePudding user response:

Create a generic query and add the where clause if needed

query = "SELECT date_num, subject, in_col FROM base"
if subjects[0] != "ALL":
    query  = f" WHERE subject in {subjects}"
  •  Tags:  
  • Related