0

I've been working with mysql for a while but I'd never come across a problem where I had to use a condition up to now. Basically I need to do this (the best way for me to explain it is to write it as if mysql supported php like conditions):

SELECT `Gender`=='male' ? '0.5' : '1' AS Col1 FROM Users

Basically I want to have a 0.5 AS Col1 for all 'males' and a 1 for all 'females'.

Eg:

UID Gender
1   male
2   female
3   male

Should return:

UID Col1
1   0.5
2   1
3   0.5

If you are wondering about the implementation. I want to recommend users "who to follow" based on their common habits. (0.5 to men means that they follow twice the number of women as men).

How can this be done?

1
  • 1
    I hope that does not mean male are only half worth as female :) Commented Aug 17, 2012 at 6:33

3 Answers 3

5

You can use

SELECT if(`Gender`='male','0.5','1') AS Col1
FROM Users

or

SELECT case when `Gender`='male'
            then '0.5'
            else '1'
       end AS Col1
FROM Users
Sign up to request clarification or add additional context in comments.

Comments

3
select uid,
    case gender
        when 'male' then '0.5'
        when 'female' then '1'
    end as genderindigit
from
    users

Comments

2

try

SELECT IF(`Gender` = 'male', '0.5', '1') AS Col1
FROM Users

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.