Bhavik P. Bhavik P. - 3 months ago 8
MySQL Question

Selecting column with opposite value of one given

I have two columns

column_a(INT)
and
column_b(INT)
. I want to do a select query that gives me the value in the column that does not contain the value I give.
For example:

column_a| column_b
5 | 10


If I were to
SELECT (something over here) FROM TABLE WHERE column_a = 10 OR column_b = 10;

The result should push out 5 (value in
column_a
.

Is this even possible?

Note: The value of 10 could be in either columns. So lets say if 10 was in
column_a
and 5 in
column_b
, the above query should still give me 5 but it would be retrieved from
column_b
instead of
column_a


Note 2: Both columns will never contain the same value.

Answer

In your contrived example, you could use a CASE statement to attempt to select the value from the two columns which does not match:

SELECT CASE WHEN column_a = 10 THEN column_b ELSE column_a END
FROM yourTable
WHERE column_a = 10 OR column_b = 10    -- this might be optional