简体   繁体   English

如何group_concat两列

[英]how to group_concat two columns

I have one table with two columns parent_string and child string like this 我有一张有两列的表parent_string和子字符串,像这样

id  parent_string             child_string
 1    0|4#festivals$Festiv     NULL
 2    0|4#festivals$Festiv     1|4@5#diwali$Deepavali
 3    0|4#festivals$Festiv     1|4@6#christmas$Christmas
 4    0|8#birthday$Birthday    1|8@9#for-mom$For Mom
 5    0|8#birthday$Birthday    1|8@10#for-dad$For Dad

If i want to select id in(1,2,3) then 如果我想在(1,2,3)中选择id

I want output concat string like following: 我想要输出concat字符串,如下所示:

0|4#festivals$Festiv~1|4@5#diwali$Deepavali~1|4@6#christmas$Christmas

how to do this? 这个怎么做?

You can use concat_ws and group concat with custom separator on the fields ... 您可以在字段上使用concat_ws和带有自定义separator group concat ...

Example : 范例

select
       concat_ws( '|', parent_string, group_concat( child_string separator '|' ) )
  from table_ame
 group by parent_string

Refer to Documentation : 请参阅文档
CONCAT_WS(separator,str1,str2,...) CONCAT_WS(分离器,STR1,STR2,...)

  • CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). CONCAT_WS()代表用分隔符连接,是CONCAT()的一种特殊形式。 The first argument is the separator for the rest of the arguments. 第一个参数是其余参数的分隔符。 The separator is added between the strings to be concatenated. 分隔符被添加到要连接的字符串之间。 The separator can be a string, as can the rest of the arguments. 分隔符可以是字符串,其余参数也可以。 If the separator is NULL, the result is NULL 如果分隔符为NULL,则结果为NULL

GROUP_CONCAT(expr) GROUP_CONCAT(表达式)

  • This function returns a string result with the concatenated non-NULL values from a group. 此函数返回一个字符串结果,其中包含来自组的串联的非NULL值。 It returns NULL if there are no non-NULL values 如果没有非NULL值,则返回NULL

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

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