Nathan Cheng
Nathan Cheng

Reputation: 3

MySQL conditional concatenate based on multiple columns

I'm stumped on a proper query to get an output based on multiple columns and the conditions in those columns:

   a  b  c
1  x     x
2  x  x  
3  x

I would like the results to output, based on where the x's are in columns a, b and c:

1 a,c
2 a,b
3 a

Is this possible to do in mysql? Much appreciated

Upvotes: 0

Views: 43

Answers (2)

Jo.
Jo.

Reputation: 790

You can use the CONCAT_WS function (docs) and some IF statements.

SELECT tn.ID,
CONCAT_WS(
  ',',
  IF(tn.a='x','a',null),
  IF(tn.b='x','b',null),
  IF(tn.c='x','c',null)
) as result
FROM TableName tn;

Upvotes: 1

naffiq
naffiq

Reputation: 1050

You can use IFNULL function for that (docs). For example:

SELECT a, IFNULL(b, c) FROM table_name;

It will select a for every case and conditionally b or c, depending on it's value (it have to be not null). But I'm afraid you cannot do more than that.

Upvotes: 0

Related Questions