IF ...在WHERE子句MySQL中的ELSE [英] IF... ELSE in WHERE clause MySQL
问题描述
我正在尝试在MySQL WHERE语句中使用IF ... ELSE函数但没有成功。
I'm trying to use a IF...ELSE function in a MySQL WHERE statement without success.
我有这样的查询:
SELECT id
FROM mytable
WHERE restrcountry NOT LIKE '%*nl*%'
AND (IF languages LIKE '%*nl*%', 1, 0) = 1;
好的,这是我的IF语句查询。
Ok, this is my query with IF statement.
但是,如何使用ELSE?
However, how can I use also "ELSE"?
示例,我想做类似的事情:
Example, I would like to do something similar:
IF语言匹配 nl --->选择id字段,其中语言为 nl
IF language match nl ---> select id field where language is nl
ELSE IF语言不匹配 nl --->选择id字段,其中语言为 en
ELSE IF language NOT match nl ---> select id field where language is en
我该怎么做在MySQL查询中,请?
How can I do this in a MySQL query, please?
感谢所有人!
推荐答案
IF
的语法是:
IF(test_expr, then_expr, else_expr)
所以你可以做一些像 IF(test1,result1,IF (test2,result2,else_result))
但它不是非常易读,所以为此目的有 CASE
表达式。
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 CASE
expression for that purpose.
CASE WHEN test1 THEN result1
WHEN test2 THEN result2
ELSE else_result END
如果要调整选择列,可以直接在选择字段中使用 IF
:
If you want to condition a select column, you can use the IF
in the select fields directly:
SELECT IF(match, nl_column en_column) AS lang
FROM table
请注意,where子句中的表达式是 TRUE
或 FALSE
,所以写
Note that an expression in a where clause is either TRUE
or FALSE
, so writing
IF(expr, TRUE, FALSE)
与
expr
这篇关于IF ...在WHERE子句MySQL中的ELSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!