简体   繁体   English

MySQL基于多个列的条件连接

[英]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: 我希望根据x在a,b和c列中的位置输出结果:

1 a,c
2 a,b
3 a

Is this possible to do in mysql? 这可以在mysql中做吗? Much appreciated 非常感激

You can use the CONCAT_WS function ( docs ) and some IF statements. 您可以使用CONCAT_WS函数( docs )和一些IF语句。

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;

You can use IFNULL function for that ( docs ). 您可以IFNULL使用IFNULL函数( 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 ). 它将为每种情况选择a ,并根据其值选择条件b或c(必须not null )。 But I'm afraid you cannot do more than that. 但是,恐怕您不能做得更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM