How to write IF ELSE statement in MySQL query

How to write IF ELSE statement in MySQL query?

Something like that:

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

Then in my array, I can do this:

  $row['state'] //this should equal 1, the query should not change anything in the database, //just the variable for returning the information 
+55
mysql if-statement
Jan 06 '12 at 19:26
source share
5 answers

You probably want to use a CASE expression.

They look like this:

 SELECT col1, col2, (case when (action = 2 and state = 0) THEN 1 ELSE 0 END) as state from tbl1; 
+101
Jan 06 '12 at 19:32
source share

you should write it in SQL, not in C / PHP style

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

for use in request

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

for use in stored procedures or functions

+17
Jan 06 2018-12-12T00:
source share

You are looking for case :

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

MySQL has the syntax if ( if(action=2 and state=0, 1, 0) ), but case is more universal.

Note that as state is just a column overlay. I assume this is in the column list of your SQL query.

+12
Jan 6 '12 at 19:29
source share
 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 be the same ....

+9
Jan 21 '14 at 13:38
source share

according to the mySQL reference, this is the syntax for using the if and else statement:

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

So, regarding your request:

 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 a good example in this link: http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

0
Feb 25 '17 at 11:55
source share



All Articles