首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在MySQL查询中编写IF ELSE语句

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

Stack Overflow用户
提问于 2012-01-07 03:26:50
回答 4查看 366.8K关注 0票数 92

如何在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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-01-07 03:32:05

您可能想要使用CASE expression

它们看起来像这样:

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

Stack Overflow用户

发布于 2012-01-07 03:31:47

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

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

在查询中使用

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

在存储过程或函数中使用

票数 29
EN

Stack Overflow用户

发布于 2012-01-07 03:29:50

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

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8763310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档