MySQL 中 concat 函数

MySQL 中 concat 函数

语法:concat(str1,str2,…)

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


select concat("a","b","c");

输出:abc

注:

Mysql 的 concat 函数在连接字符串的时候,只要其中一个为 NULL 
则返回值为 NULL.

select  concat("1","2",null);

输出结果:NULL

MySQL 中 concat_ws 函数

语法:concat_ws(separator,str1,str2)

concat_ws() 代表 Concat With Separator,是 CONCAT() 的特殊形式,第一个参数是其他参数的分隔符。分隔符的位置放在要连接的两个字符串之间,分隔符可以是一个字符串,也可以是一个其他参数。

注意:如果分隔符为 NULL ,则结果为 NULL 。函数会忽略任何分隔符参数后的 NULL 值。


eg:字符串连接后以逗号分隔

select concat_ws(",","1","2","3");

输出结果: 1,2,3

与 Mysql 中 concat 函数不同的是,concat_ws 函数在执行的时候,
不会因为 NULL 值而返回 NULLselect concat_ws(",","1","2",NULL);

输出结果: 1.2



MySQL 中 group_concat 函数

语法:group_concat([DISTINCT]) 要连接的字段 [order by asc/desc 排序字段] [Separator ‘分隔符’]


eg: tableTest:有 id name 字段

select * from tableTest;
输出结果:
         id   name
         1     10
         1     20
         1	   20
         2     20
         3     200
         3     500

1. 以 id 分组,把 name 字段的值打印在一起,逗号分隔(默认)

    select id, group_concat(name) from tableTest group by id;

    输出结果:
            id  group_concat(name)
            1     10,20,20
            2     20
            3     200,500
		
2. 以 id 分组,把 name 字段的值打印在一行,分号分隔。

    select id,group_concat(name separator';') from tableTest group by id;

            id     group_concat(name separator';')
            1      10;20;20
            2      20
            3      200;500
		 
		 
3. 以 id 分组,把冗余的 name 字段的值打印在一行,逗号分隔。

    select id,group_concat(distinct name) from tableTest group by id;

    输出结果:
            id     group_concat(distinct name)
            1       10,20
            2       20
            3       200,500
             
4. 以 id 分组,把 name 字段的值打印在一行,逗号分隔,以 name 排倒序

	select id,group_concat(name order by name desc) from tableTest group by id;
	
	输出结果:
			id    group_concat(name order by name desc)
			1       20,20,10
			2       20
			3       500,300
			 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值