IF...ELSE 在 WHERE 子句 MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15683185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IF... ELSE in WHERE clause MySQL
提问by David Madhatter
I'm trying to use a IF...ELSE function in a MySQL WHERE statement without success.
我试图在 MySQL WHERE 语句中使用 IF...ELSE 函数但没有成功。
I have this query:
我有这个查询:
SELECT id
FROM mytable
WHERE restrcountry NOT LIKE '%*nl*%'
AND (IF languages LIKE '%*nl*%', 1, 0) = 1;
Ok, this is my query with IF statement.
好的,这是我使用 IF 语句的查询。
However, how can I use also "ELSE"?
但是,我怎样才能使用“ELSE”?
Example, I would like to do something similar:
例如,我想做类似的事情:
IF language match nl---> select id field where language is nl
如果语言匹配nl---> 选择语言为nl 的id 字段
ELSE IF language NOT match nl---> select id field where language is en
ELSE 如果语言不匹配nl---> 选择语言为en 的id 字段
How can I do this in a MySQL query, please?
请问如何在 MySQL 查询中执行此操作?
Thanks to all!
谢谢大家!
回答by didierc
The syntax for IFis :
的语法IF是:
IF(test_expr, then_expr, else_expr)
so you could do something like IF(test1, result1, IF(test2, result2, else_result))but it would not be very readable, so there's the CASEexpression for that purpose.
所以你可以做类似的事情,IF(test1, result1, IF(test2, result2, else_result))但它不会很可读,所以有CASE这个目的的表达。
CASE WHEN test1 THEN result1
WHEN test2 THEN result2
ELSE else_result END
If you want to condition a select column, you can use the IFin the select fields directly:
如果要条件选择列,可以IF直接在选择字段中使用:
SELECT IF(match, nl_column en_column) AS lang
FROM table
Note that an expression in a where clause is either TRUEor FALSE, so writing
请注意 where 子句中的表达式是TRUEor FALSE,所以写作
IF(expr, TRUE, FALSE)
is the same as
是相同的
expr
回答by sasi
use CASE instead
改用 CASE
CASE
WHEN languages LIKE '%*nl*%' THEN 1
WHEN languages NOT LIKE '%*nl*%' THEN 0
END as languages

