concat,concat_ws,group_concat function usage

concat,concat_ws,group_concat function usage

1. concat() function

Employees query under the department organization tree structure. Click the department tree node on the left to query how many employees there are.
Function: Splice multiple strings into one string.
Syntax: concat(str1, str2,…)
The return result is the string generated by the connection parameter.
If If any parameter is NULL, the return value is NULL.

## 例子一
select concat(name,score) from test_table;
## 例子二
select concat(name,'-',score) from test_table;

Note: If there are more parameters, more - symbols are needed, so concat_ws() is needed.

2. concat_ws() function

Function: Specify the separator at one time.
Syntax: concat_ws(separator,str1,str2,…)
Description: The first parameter specifies the separator. The separator cannot be empty. If it is NULL, the return value is NULL.

## 分隔符号为{-}
select concat_ws('-',name,score) from test_table;
## 分隔符号为{null空值}===》结果为null
select concat_ws(null,name,score) from test_table;

3. group_concat() function

1. Function: Concatenate the values ​​in the same group generated by group by and return a string result
2. Syntax group_concat([distinct] field to be connected [order by sorting field asc/desc] [separator'separator'] )
Note: Duplicate values ​​can be excluded by using distinct. If you want to sort the values ​​in the results, you can use the order by clause. The separator is a string value. The default is a
comma.


If your SQL level is higher, go directly to the fourth one. If your
SQL level is higher, go directly to the fourth one.
Note:
Pay attention to whether the commas and double quotes in the following SQL statements are in English. Copy them to the editor and edit them yourself. Modify:
Pay attention to whether the commas and double quotes in the following SQL statements are in English. Copy them to the editor and modify them yourself.


## 一: group_concat()函数例子-使用group_concat()和group by显示相同名字的人的id号
select name,group_concat(id) from test_table group by name;

## 二:group_concat()函数例子-将上面的id号从小到大排序 且用'_'作为分隔符
select name,group_concat(id order by id asc '_') from test_table group by name;

## 三:id,score同时
select name,group_concat(id,score order by id asc '_') from test_table group by name;

## 四:id,score同时
select name,group_concat(concat_ws('_',id,score) order by id asc '_') from test_table group by name;



## 简单例子-包含在group by语句后面作为分组的依据
select name,min(id) from test_table  group by name;

Guess you like

Origin blog.csdn.net/weixin_44188105/article/details/131855076