Mysql concat() group_concat()用法

数据库表:

关键字:concat

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

使用:concat(column1, column2,...)  字段中间可以加连字符

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

测试:如下

select concat(name,description) from test

 select concat(name,' ----> ',description) from test

关键字:concat_ws (ws就是with separator的缩写 译位 使用连字符)

功能:和concat()一样,使用分隔符在相邻的字段之间进行拼接~ 适用于拼接多个字段的情况

使用:concat_ws(separator, column1, column2, ...) 第一个参数指定 分隔符 其他参数是字段

注意:分隔符不能为null,如果为null,则返回结果为null

测试:如下

select concat_ws(' * ',name,description) as col from test

 select concat_ws(null,name,description) as col from test

关键字:group_concat

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

使用:group_concat( distinct column order by column asc/desc separator '分隔符' ) 最关键的是红色部分  其他可选 distinct去除重复值  order by column 按照 column排序ssc升序 desc降序

测试:如下

select id,name,group_concat(hobby separator ',') as occu from test group by name

 首先把hobby换成数字 方便测试 排序

 select id,name,group_concat(hobby order by hobby asc separator ',') as occu from test group by name

  select id,name,group_concat(hobby order by hobby desc separator ',') as occu from test group by name

 select id,name,group_concat(distinct hobby order by hobby asc separator ',') as occu from test group by name

猜你喜欢

转载自www.cnblogs.com/xuchao0506/p/13171584.html