mysql函数 字段拼接concat()、concat_ws()

2020-11-27  本文已影响0人  爱折腾的傻小子
concat()函数
-- 拼接字段 area、fr、best_history_data
select concat(area,fr,best_history_data) from test_concat order by id limit 5;
-- 想在字段间添加分隔符,需要在每两个字段间都添加一个分隔符
select concat(area,',',fr,',',best_history_data) as test_result from test_concat order by id limit 5;

concat_ws()函数
-- 已英文逗号分隔字段area、fr、best_history_data
select concat_ws(',',area,fr,best_history_data) from test_concat order by id limit 5;
-- 和MySQL中concat函数不同的是, concat_ws函数在执行的时候,不会因为NULL值而返回NULL 
select concat_ws(',','11','22',NULL);
/*
+-------------------------------+
| concat_ws(',','11','22',NULL) |
+-------------------------------+
| 11,22 |
+-------------------------------+
1 row in set (0.00 sec)
*/

group_concat()函数
/*
+-------------------------------+
| id | age | name |
+-------------------------------+
| 1 | 30 | 啊啊啊 |
| 2 | 50 | 是是是 |
| 3 | 55 | 张学友 |
| 4 | 55 | 郭富城 |
+-------------------------------+
1 row in set (0.00 sec)
*/
-- 根据area分组,拼接每个区域各个指标的指标值
select GROUP_CONCAT(id,name) from t_user GROUP BY age;
/*
+-------------------------------+
| GROUP_CONCAT(id,name) |
+-------------------------------+
| 1啊啊啊 |
| 2是是是 |
| 3张学友,4郭富城 |
+-------------------------------+
1 row in set (0.00 sec)
*/
select GROUP_CONCAT(id,name separator '-') from t_user GROUP BY age;
/*
+-------------------------------+
| GROUP_CONCAT(id,name) |
+-------------------------------+
| 1啊啊啊 |
| 2是是是 |
| 3张学友-4郭富城 |
+-------------------------------+
1 row in set (0.00 sec)
*/
select GROUP_CONCAT(concat_ws('-|-',id,name) separator '&') from t_user GROUP BY age;
/*
+-------------------------------+
| GROUP_CONCAT(concat_ws('-|-',id,name) separator '&') |
+-------------------------------+
| 1-|-啊啊啊 |
| 2-|-是是是 |
| 3-|-张学友&4-|-郭富城 |
+-------------------------------+
1 row in set (0.00 sec)
*/
select GROUP_CONCAT(concat_ws('-|-',id,`name`) order by `id` asc separator '&') from t_user GROUP BY age;
/*
+-------------------------------+
| GROUP_CONCAT(concat_ws('-|-',id,`name`) order by `id` asc separator '&') |
+-------------------------------+
| 1-|-啊啊啊 |
| 2-|-是是是 |
| 3-|-张学友&4-|-郭富城 |
+-------------------------------+
1 row in set (0.00 sec)
*/
select GROUP_CONCAT(concat_ws('-|-',id,`name`) order by `id` desc separator '&') from t_user GROUP BY age;
/*
+-------------------------------+
| GROUP_CONCAT(concat_ws('-|-',id,`name`) order by `id` asc separator '&') |
+-------------------------------+
| 1-|-啊啊啊 |
| 2-|-是是是 |
| 4-|-郭富城&3-|-张学友 |
+-------------------------------+
1 row in set (0.00 sec)
*/

参考来源:yuandian43

上一篇下一篇

猜你喜欢

热点阅读