Reputation: 48711
How can I use the if
statement in MYSQL query to return yes
if it's true and no
if it's not?
See the example :
IF(table_name.field_name_value = 1, 'yes','no') AS active
I'm trying something like this but with no success
Upvotes: 0
Views: 122
Reputation: 137350
From the documentation on IF()
function:
mysql> SELECT IF(1<2,'yes','no');
-> 'yes'
So, basically, the syntax is as mentioned above.
EDIT:
You are saying my example is incorrect. Thus, I provide you a proof (which proves the example from the documentation I mentioned above):
I have a table, which has uid
column, containing ID of the user. The table is part of the database on some site (which is not relevant). When I make the following query:
SELECT `uid`, IF(`uid`=3, 'yes', 'no') AS `active` FROM `mysite_users`;
I receive the following result:
+-----+--------+
| uid | active |
+-----+--------+
| 0 | no |
| 1 | no |
| 3 | yes |
| 8 | no |
| 9 | no |
| 10 | no |
| 11 | no |
| 12 | no |
| 13 | no |
| 14 | no |
| 15 | no |
+-----+--------+
11 rows in set (0,00 sec)
Which is exactly what I would expect (and what should be expected after reading the documentation). Is it still not working for you?
Upvotes: 1
Reputation: 23624
See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
SELECT CASE WHEN table_name.field_name_value = 1 THEN 'yes'
ELSE 'no' END;
Upvotes: 1
Reputation: 100175
You can use CASE in mysql query for that. Like
CASE WHEN table_name.field_name_valud = 1 THEN 'Yes' ELSE 'No' END As active
Upvotes: 1
Reputation: 181290
You can use case
function:
select case
when table_name.field_name_value = 1 then 'yes'
else 'no'
end case as active
from table_name
Although if
function should also work. Can you post your full query?
Upvotes: 1