1

I have a table with 5 columns - col1, co12,... I have 5 search parameters searching on each column. I need to write a mySQL query that will return me the results of all matches. If I do not provide a value for a search parameter it is ignored.

I had this but it does not work

select * from tableA
where ((col1 IS NULL AND srch1 IS NULL) OR (col1 like srch1))
and ((col2 IS NULL AND srch2 IS NULL) OR (col2 like srch2))
etc...

3 Answers 3

0
Select * from tableA where
col1 like '%' + Coalesce(srch1,col1) + '%' and
col2 like '%' + Coalesce(srch2,col2) + '%'
0

I assume that by "not work" you mean the like part of your conditions isn't working.

That would be because you must wrap your search string with % characters to form a "like" search term. Try this:

select * from tableA
where ((col1 IS NULL AND srch1 IS NULL) OR col1 like concat('%', srch1, '%'))
and ((col2 IS NULL AND srch2 IS NULL) OR col2 like concat('%', srch2, '%'))
etc...


You were pretty close!

0

By having each condition OR'd with itself in parens, and testing for the null first, that would pre-qualify the condition and ignore the other half. If there IS a value, then it is tested against the corresponding column. Now, that said, if you really need a "LIKE" qualifier, then you may need to expect, or tack on the '%' for wildcard matching.

select
      A.* 
   from 
      tableA  A
   where 
          (srch1 is null OR col1 like srch1)
      AND (srch2 is null OR col2 like srch2)
      AND (srch3 is null OR col3 like srch3)
      AND (srch4 is null OR col4 like srch4)
      AND (srch5 is null OR col5 like srch5)

So, if you only provided srch3 parameter, then the answer would interpreted as

where 
       TRUE
   and TRUE
   and col3 like srch3
   and TRUE
   and TRUE

since the srch? is null would be true first, and ignore the rest of that test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.