Skip to content
Advertisement

single or multiple search with a single query based on condition

For example i have this table component_information with these atrribute

                             1.id
                             2.group_code
                             3.Category_code
                             4.component_code
                             5.description

I will pass the group_code,category_code,compnent_code from the frontend for searching.Now i want to do single or multiple search based on this. Like on first condition if it gets only group_code value from frontend it will do search only based on group_code.On second condition,If it gets group_code and category_code then it will do multiple search ignore the first condition and so on.But my query only returning value for first condition only even if it gets multiple value.Is there any way to do it in a single query or i have to write separate query for every condition>here is what i have done so far

     try:
                print('getAllComponentSearch...')

                groupCode = request.args.get('groupCode ', None)
                categoryCode= request.args.get('categoryCode', None)
                componentCode= request.args.get('componentCode', None)

         connection = db.engine.connect(close_with_result=True)
         sql = text("""select ci.id, ci.description,ci.group_code,ci.category_code, 
                       ci.component_code
                       from component_information ci 
                       where ((ci.group_code=:groupCode ) OR 
                  (ci.group_code=:groupCode AND ci. category_code = categoryCode)) OR 
           ((ci.group_code=:groupCode )AND ci. category_code = categoryCode And 
            ci.component_code =: componentCode))order by ci.id""")

       dbcomponentInfoList = connection.execute(sql,groupCode =groupCode ,categoryCode =categoryCode ,componentCode=componentCode).fetchall()
                connection.close()

Advertisement

Answer

You are having a generic SQL statement with multiple OR conditions. I would suggest you to dynamically construct the SQL Statement based on request arguments.

sql = text("""select ci.id, ci.description,ci.group_code,ci.category_code, 
                       ci.component_code
                       from component_information ci 
                       where 1=1 """)

IF NOT groupCode AND NOT categoryCode AND NOT componentCode :
   sql = sql + " AND ( (ci.group_code=:groupCode AND ci. category_code = categoryCode AND `
      ci.component_code =: componentCode))"
ELIF  NOT groupCode AND NOT categoryCode :
   sql = sql + " AND (ci.group_code=:groupCode AND ci. category_code = categoryCode)"
ELIF NOT groupCode:
   sql = sql + " AND  (ci.group_code=:groupCode)"
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement