MySQL where语句基于if

MySQL where statement based on if

您好,我正在根据以下逻辑做出 MySQL 陈述。

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

逻辑很简单,如果描述列是教育性的,过滤器应该有字符串 "EDU2015. Else, it should filter with the serial of "NOVEL2015"

我不确定我是否使用 mysql 中使用 IF 语句的方式,但我不知道在哪里放置 https://dev.mysql.com/doc/refman/5.7/en/if.html

中的 where 语句

您可以像这样使用 CASE 表达式:

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

请注意,当您比较值时,需要一个等号而不是两个。

编辑:如果你想根据条件过滤不同的列,你可以使用这个:

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

您可以像这样在 WHERE 块中使用 IF

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

或者您可以选择 CASE WHEN 表达式,如@sagi 所述。

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