Dyl*_*oss 80 mysql if-statement
如何在MySQL查询中编写IF ELSE语句?
像这样的东西:
mysql_query("...(irrelevant code).. IF(action==2&&state==0){state=1}");
Run Code Online (Sandbox Code Playgroud)
然后在我的数组中我应该能够这样做:
$row['state']
//this should equal 1, the query should not change anything in the database,
//just the variable for returning the information
Run Code Online (Sandbox Code Playgroud)
Jac*_*nds 146
您可能想要使用CASE表达式.
它们看起来像这样:
SELECT col1, col2, (case when (action = 2 and state = 0)
THEN
1
ELSE
0
END)
as state from tbl1;
Run Code Online (Sandbox Code Playgroud)
Ser*_*geS 27
你必须用SQL写它而不是C/PHP风格
IF( action = 2 AND state = 0, 1, 0 ) AS state
Run Code Online (Sandbox Code Playgroud)
用于查询
IF ( action = 2 AND state = 0 ) THEN SET state = 1
Run Code Online (Sandbox Code Playgroud)
用于存储过程或函数
Eri*_*ric 15
您正在寻找case:
case when action = 2 and state = 0 then 1 else 0 end as state
Run Code Online (Sandbox Code Playgroud)
MySQL有一个if语法(if(action=2 and state=0, 1, 0)),但case更通用.
请注意,as state只有列的别名.我假设这是在您的SQL查询的列列表中.
Kha*_*azi 15
SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;
Run Code Online (Sandbox Code Playgroud)
要么
SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;
Run Code Online (Sandbox Code Playgroud)
两个结果都一样....
小智 6
根据mySQL参考手册,这个使用if和else语句的语法:
Run Code Online (Sandbox Code Playgroud)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);
Run Code Online (Sandbox Code Playgroud)
或者你可以使用
IF ((action=2)&&(state=0)) then
state = 1;
ELSE
state = 2;
END IF;
Run Code Online (Sandbox Code Playgroud)
这个链接有很好的例子:http: //easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/