SQL CONCAT() 和 GROUP_CONCAT() 函数介绍

367人浏览 / 0人评论
一、concat()函数

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

语法1:concat(str1, str2,...)  

返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null。

语法2:concat(str1, seperator,str2,seperator,...)

返回结果为连接参数产生的字符串并且有分隔符,如果有任何一个参数为null,则返回值为null。

二、concat_ws()函数

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

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

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

三、group_concat()函数

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

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

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

应用介绍:

drop table if exists t_orders;
 
create table t_orders (
id int primary key auto_increment,
userId int,
orderId varchar(20)
);

insert into t_orders(userId, orderId) values(1, '100');

insert into t_orders(userId, orderId) values(1, '101');

insert into t_orders(userId, orderId) values(1, '102');


insert into t_orders(userId, orderId) values(2, '200');

insert into t_orders(userId, orderId) values(2, '201');

insert into t_orders(userId, orderId) values(3, '300');
普通查询
select userId as 用户ID, orderId as 订单 from t_orders;  

result1.png

以 userId 分组,把 orderId 字段的值打印在一行,逗号分隔
select userId as 用户ID, group_concat(orderId) as 订单 from t_orders group by userId;  

result2.png

以 userId 分组,把 orderId 字段的值打印在一行,分号分隔
select userId as 用户ID, group_concat(orderId separator ';') as 订单 from t_orders group by userId;

result3.png

以 userId 分组,把 orderId 字段的值打印在一行,降序排列
select userId as 用户ID, group_concat(orderId order by orderId desc) as 订单列表 from t_orders group by userId;

result4.png

全部评论

晴天下起了小雨
2017-10-01 18:00
很喜欢,果断关注了
wjmyly7336064
2017-10-01 18:00
相当实用,赞美了
橘大佬
2017-10-01 18:00
就是有些细节再到位点就好了…