3

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

2

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

@UzumakiNaruto Actually CASE is ANSI SQL, so I think all versions support it
Thanks! it works. But what if i need a different filter for different condition? Let's say. Select * from content if(description=='educational') where serial like '%EDU2015%' else where id >100
5

You can use IF in WHERE block like that:

Select * 
from content 
where serial like IF(description = 'educational','%EDU2015%','%NOVEL2015%');

Alternatively you can choose CASE WHEN expression like @sagi stated.

enter image description here

mysql> SELECT IF(1>3,'true','false');
+------------------------+
| IF(1>3,'true','false') |
+------------------------+
| false                  | 
+------------------------+
1 row in set (0.00 sec)

Comments

2

This works too

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.