MySQL的concat、concat_ws、group_concat函数

CONCAT()函数

将多个字符串连接成一个字符串。如果有任何一个参数为null,则返回值为null。

语法

CONCAT(str1, str2, …)

举例
select concat(id, name, score) as info from tt2;

CONCAT_WS()函数

和concat()一样,将多个字符串连接成一个字符串,不同的是可以指定分隔符。

语法

CONCAT_WS(separator, str1, str2, …)

举例
select concat_ws(',', id, name, score) as info from tt2;

GROUP_CONCAT()函数

将group by产生的同一个分组中的值连接起来,返回一个字符串结果。
通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;使用separator可以指定分隔符,缺省为一个逗号。

语法

group_concat([DISTINCT] 字段名 [Order BY 排序字段 ASC/DESC] [Separator ‘分隔符’])

举例
select name, group_concat(distinct id) from tt2 group by name;
+-------+------------------+
| name  | group_concat(id) |
+-------+------------------+
| jack  | 1,2,3            |
| marry | 4,5,6,7,8        |
+-------+------------------+

select name, group_concat(id order by id desc separator '_') from tt2 group by name;
+-------+-------------------------------------------------+
| name  | group_concat(id order by id desc separator '_') |
+-------+-------------------------------------------------+
| jack  | 3_2_1                                           |
| marry | 8_7_6_5_4                                       |
+-------+-------------------------------------------------+

select name, group_concat(concat_ws('-', id, score) order by id desc) from tt2 group by name;
+-------+----------------------------------------------------------+
| name  | group_concat(concat_ws('-', id, score) order by id desc) |
+-------+----------------------------------------------------------+
| jack  | 3-80,2-75,1-70                                           |
| marry | 8-82,7-70,6-62,5-85,4-80                                 |
+-------+----------------------------------------------------------+
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值