Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: value based on conditions

I have a MySQL query where I would like it to have a pseudo column returned which is based off of:

  • If columnW does not equal 0, it should be 1 BUT
  • If columnX does not equal 0, it should be 2 BUT
  • If columnY does not equal 0, it should be 3 BUT
  • If columnZ does not equal 0, it should be 4

Hopefully that makes sense. My SQL isn't good enough to wrap my head around this.

like image 585
Tim Cooper Avatar asked Feb 28 '10 20:02

Tim Cooper


2 Answers

Try using a case expression:

SELECT CASE WHEN columnZ <> 0 THEN 4
            WHEN columnY <> 0 THEN 3
            WHEN columnX <> 0 THEN 2
            WHEN columnW <> 0 THEN 1
            ELSE 0
       END AS your_alias_name
FROM ...
like image 101
Mark Byers Avatar answered Oct 25 '22 23:10

Mark Byers


You can use CASE ... WHEN to do this.

See

mysql> SELECT CASE 1 WHEN 1 THEN 'one'
    ->     WHEN 2 THEN 'two' ELSE 'more' END;
        -> 'one'
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
        -> 'true'
mysql> SELECT CASE BINARY 'B'
    ->     WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
        -> NULL
like image 31
road242 Avatar answered Oct 25 '22 23:10

road242