Reputation: 509
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
Upvotes: 3
Views: 14467
Reputation: 143
This works too
Select * from content
where if(description = 'educational', serial like '%EDU2015%', serial like '%NOVEL2015%');
Upvotes: 2
Reputation: 40481
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)
Upvotes: 5
Reputation: 13519
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.
mysql> SELECT IF(1>3,'true','false');
+------------------------+
| IF(1>3,'true','false') |
+------------------------+
| false |
+------------------------+
1 row in set (0.00 sec)
Upvotes: 5