concat 函数:
直接合并n个字段
select concat("你好","明天","后天") filed;
返回:
你好明天后天
select concat("你好","明天","后天",null) filed;
返回:
null
concat_ws函数:
以指定字符连接n个字符串或字段
select concat_ws("_","你好","明天","后天") filed;
返回:
你好_明天_后天
select concat_ws("_","你好","明天","后天",null) filed;
返回:
你好_明天_后天
和concat不同的是, concat_ws函数在执行的时候,不会因为NULL值而返回NULL
mysql中的 group_concat()
*必须将group by按照什么东西排序,也打印出来;否则函数不起作用
可用来行转列
group_concat([DISTINCT] 要连接的字段[Order BY ASC/DESC 排序字段] [Separator ‘分隔符’])
create table aa(
id int,
name VARCHAR(255));
insert into aa values(1,10);
insert into aa values(1,10);
insert into aa values(1,20);
insert into aa values(1,30);
insert into aa values(3,30);
insert into aa values(5,60);
insert into aa values(5,90);
insert into aa values(6,990);
实例:
--1.以id分组,把name字段的值打印在一行,逗号分隔(默认)
select id,group_concat(name) from aa group by id;
结果:
1 10,10,20,30
3 30
5 60,90
6 990
--2 以id分组,把name字段的值打印在一行,分号分隔
select id,group_concat(name separator ';') from aa group by id;
1 10;10;20;30
3 30
5 60;90
6 990
--3 以id分组,把去冗余的name字段的值打印在一行,逗号分隔
select id,group_concat(distinct name separator ';') from aa group by id;
1 10;20;30
3 30
5 60;90
6 990
--4 以id分组,把name字段的值打印在一行,*号分隔,以name排倒序
select id,group_concat(name order by name desc separator "*") from aa group by id
1 30*20*10*10
3 30
5 90*60
6 990