Search code examples
mysqlif-statementwhere-clause

MySQL where statement based on if


Hi I'm making an MySQL statement from the following logic.

Select * from content 
if(description=='educational')
where serial like '%EDU2015%'
else where serial like '%NOVEL2015%'

The logic is simply as, if the description column is educational, the filter should have the string "EDU2015. Else, it should filter with the serial of "NOVEL2015"

I'm not sure if im using the way to use the IF statement in mysql but i dont know where to place the where statements from https://dev.mysql.com/doc/refman/5.7/en/if.html


Solution

  • You can use CASE expression like this:

    SELECT * FROM content
    WHERE serial like CASE WHEN description = 'educational'
                           THEN '%EDU2015%'
                           ELSE '%NOVEL2015%'
                      END
    

    Note that when you compare values, a single equal sign is required and not two.

    EDIT: If you want to filter on different columns based on a condition, you can use this:

    SELECT * FROM content
    WHERE (description = 'educational' and  serial like '%EDU2015%')
        OR(description <> 'educational' and id>100)