开发者

Is there such thing as a SELECT with an IF/ELSE statement in mySQL?

Is it possible to have a SELECT statement in mySQL with an IF/ELSE clause in it?

E.g.

I want to SELECT all table rows and return color2 ONLY if color2 is 'brown'. My example SQL select statement of what I would like to accomplish is below.

APPLES
+------+--------+----------+----------+  
|  ID  |  NAME  |  COLOR1  |  COLOR2  |  
开发者_JS百科+------+--------+----------+----------+  
|  1   | apple1 |    red   |   brown  |
+------+--------+----------+----------+  
|  2   | apple2 |    red   |   green  |
+------+--------+----------+----------+  

SELECT name, (IF color2 = 'brown' SELECT color2 ELSE SELECT color1) AS color FROM apples

would return:

+----------+----------+
|  apple1  |   brown  |
+----------+----------+
|  apple2  |    red   |
+----------+----------+


MySQL has an IF() function:

SELECT name, IF(color2='brown', color2, color1) AS color FROM apples


Use:

SELECT a.name, 
       CASE WHEN a.color2 = 'brown' THEN a.color2 ELSE a.color1 END AS color 
  FROM apples a

Reference: CASE

The CASE statement allows for IF/ELSE or SWITCH-like functionality, and has the benefit of being ANSI standard. That query would work on SQL Server, Oracle, MySQL...


Check out the CASE statement in the MySQL Reference Manual.


The Control Flow Function documentation should help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜