2009-12-14 86 views
1
 
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 

+0

Wont 5> 0總是導致'true',因此EQ_Type?我不太瞭解MySql,所以我可能會誤解它。這只是一個人爲的例子嗎? – GrayWizardx 2009-12-14 01:35:07

回答

3

只刪除單引號。在這種情況下CASE statements - -

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

謝謝先生。我是新手,所以我認爲這將是明顯的。 – 2009-12-14 01:23:22

1

我建議使用ANSI符號,而不是MySQL的特定語法:

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

原因是,如果你改變了數據庫 - 這種說法不會需要改變工作在Oracle,Postgres,SQL Server等上。