MySQL中的字段拼接 concat() concat_ws() group_concat()函数

  • 1.concat()函数
  • 2.concat_ws()函数
  • 3.group_concat()函数 

操作的table

select * from test_concat order by id limit 5;

1.concat()函数

功能:将多个字符串连接成一个字符串。

语法:concat(str1, str2,...),返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null

3、举例:

select concat(area,fr,best_history_data) from test_concat order by id limit 5;

如果想在字段间加分隔符,需要在每两个字段间都增加一个分隔符,比较麻烦:

select concat(area,',',fr,',',best_history_data) as test_result from test_concat order by id limit 5;

2.concat_ws()函数

功能:和concat()一样,将多个字符串连接成一个字符串,但是可以一次性指定分隔符~(concat_ws就是concat with separator)

语法:concat_ws(separator, str1, str2, ...)

说明:第一个参数指定分隔符。需要注意的是分隔符不能为null,如果为null,则返回结果为null

select concat_ws(',',area,fr,best_history_data) from test_concat order by id limit 5;


注意:和MySQL中concat函数不同的是, concat_ws函数在执行的时候,不会因为NULL值而返回NULL 

mysql> select concat_ws(',','11','22',NULL);
+-------------------------------+
| concat_ws(',','11','22',NULL) |
+-------------------------------+
| 11,22 |
+-------------------------------+
1 row in set (0.00 sec)

3.group_concat()函数

功能:将group by产生的同一个分组中的值连接起来,返回一个字符串结果。

语法:group_concat[distinct要连接的字段 [order by 排序字段 asc/desc  [separator '分隔符')

通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。

测试table

select * from test_table;

1.根据area分组,拼接每个区域各个指标的指标值

select group_concat(fr,best_history_data) from test_table group by area;

2.增加分割符

select group_concat(fr,best_history_data separator '|') from test_table group by area;

3.结合concat_ws()函数,在fr与best_history_data之间增加分割符-

select group_concat(concat_ws('-',fr,best_history_data) separator '|') from test_table group by area;

4.根据best_history_data进行排序

select group_concat(concat_ws('-',fr,best_history_data) order by best_history_data desc separator '|') from test_table group by area;

posted @ 2019-11-08 16:22  声声慢43  阅读(27939)  评论(0编辑  收藏  举报