如何在MySQL查询中编写IF ELSE语句

时间:2012-01-06 19:26:50

标签: mysql if-statement

如何在MySQL查询中编写IF ELSE语句?

这样的事情:

mysql_query("...(irrelevant code).. IF(action==2&&state==0){state=1}");

然后在我的阵列中我应该能够做到这一点:

 $row['state'] 
//this should equal 1, the query should not change anything in the database, 
//just the variable for returning the information

5 个答案:

答案 0 :(得分:138)

您可能想要使用CASE expression

他们看起来像这样:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

答案 1 :(得分:24)

你必须用SQL写它而不是C / PHP风格

IF( action = 2 AND state = 0, 1, 0 ) AS state

用于查询

IF ( action = 2 AND state = 0 ) THEN SET state = 1

用于存储过程或函数

答案 2 :(得分:14)

您正在寻找case

case when action = 2 and state = 0 then 1 else 0 end as state

MySQL有if语法(if(action=2 and state=0, 1, 0)),但case更通用。

请注意,as state只是对列进行别名。我假设这是在您的SQL查询的列列表中。

答案 3 :(得分:13)

SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;

OR

SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;

两个结果都一样....

答案 4 :(得分:5)

根据mySQL参考手册,这是使用if和else语句的语法:

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

关于您的查询:

x = IF((action=2)&&(state=0),1,2);

或者您可以使用

IF ((action=2)&&(state=0)) then 
state = 1;
ELSE 
state = 2;
END IF;

这个链接有很好的例子: http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/