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

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

像这样的东西:

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

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

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

您可能想要使用CASEexpression式 。

他们看起来像这样:

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

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

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

用于查询

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

用于存储过程或函数

你正在寻找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查询的列列表中。

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

要么

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

两个结果都一样….

根据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/