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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8763310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:17:04  来源:igfitidea点击:

How do write IF ELSE statement in a MySQL query

mysqlif-statement

提问by Dylan Cross

How do I write an IF ELSE statement in a MySQL query?

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

Something like this:

像这样的东西:

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

Then down in my array I should be able to do this:

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

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

回答by Hyman Edmonds

You probably want to use a CASEexpression.

您可能想要使用CASE表达式

They look like this:

它们看起来像这样:

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

回答by SergeS

you must write it in SQL not it C/PHP style

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

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

for use in query

用于查询

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

for use in stored procedures or functions

用于存储过程或函数

回答by Eric

You're looking for case:

您正在寻找case

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

MySQL has an ifsyntax (if(action=2 and state=0, 1, 0)), but caseis more universal.

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

Note that the as statethere is just aliasing the column. I'm assuming this is in the column list of your SQL query.

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

回答by Khandad Niazi

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;

both results will same....

两个结果都一样....

回答by Dilraj Singh

according to the mySQL reference manual this the syntax of using if and else statement :

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

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

So regarding your query :

所以关于你的查询:

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

or you can use

或者你可以使用

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

There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

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