MYSQL if语句问题

时间:2009-12-14 01:17:31

标签: mysql if-statement

Is there any way to get the if statement to evaluate a query?

SELECT if(5>0,'EQ_Type','*') FROM EQUIPMENT;

Resulting in:
+-----------------------+
| IF(5>0,'EQ_Type','*') |
+-----------------------+
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
| EQ_Type               |
+-----------------------+
9 rows in set (0.00 sec)




I would like the above statement to be equivalent to the following:

SELECT 'EQ_Type' FROM EQUIPMENT;

And produce:
+--------------+
| EQ_Type      |
+--------------+
| ENGINE       |
| ENGINE       |
| ENGINE       |
| TRAILER      |
| TRAILER      |
| TRAILER      |
| WATER TENDER |
| WATER TENDER |
| WATER TENDER |
+--------------+


Thanks for any help

2 个答案:

答案 0 :(得分:3)

只需删除单引号。

SELECT if(5>0,EQ_Type,'*') FROM EQUIPMENT;

答案 1 :(得分:1)

我建议在这种情况下使用ANSI表示法 - CASE statements - 而不是MySQL特定的语法:

SELECT CASE WHEN 5 > 0 THEN t.eq_type ELSE '*' END
  FROM EQUIPMENT t

原因是,如果您更改了数据库,则无需将此语句更改为可在Oracle,Postgres,SQL Server等上使用。