您的位置:首页 > 数据库 > MySQL

MySQL用逗号进行拼接、以逗号进行分割

2020-06-10 10:14 82 查看

MySQL中,把查询的结果拼接成一个字符串。

  •  group_concat 函数

     用法:group_concat (待拼接对象)

     输出:用逗号进行拼接后的字符串

     例子:

[code]select group_concat(emp_no) as employees from dept_emp;

/*
结果:
employees                                                         |
+-------------------------------------------------------------------+
| 10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10010 |
+-------------------------------------------------------------------+

*/

可以使用MySQL中的字符串拆分函数实现:

  • substring_index(str,delim,count)

     说明:str: 被分割的字符串; delim: 分隔符; count: 分割符出现的次数

     例子:对于字符串 “209755,209756,209757” ,设置delim为 “,”,count为1,就会返回 “209755”;

               其它参数不变,count为2,就会返回 “209755,209756”;其它参数不变,count为-1,就会返回 “209757”。

[code]select colnum_name
,(select substring_index(substring_index(bill_ids,',',1),',',-1)) as bill_id1
,(select substring_index(substring_index(bill_ids,',',2),',',-1)) as bill_id2
,(select substring_index(substring_index(bill_ids,',',3),',',-1)) as bill_id3
from table_name;

若不知道要分割的字段究竟有几个值(如可能某些行就1个值,某些有6个),可以考虑根据具有最多值的数量来选择使用多少条

(select substring_index(substring_index(bill_ids,’,’,第几个值),’,’,-1))语句,但是会有问题(待解决)

例子:

原表
1
2,3,4
5,6
分割的结果
1 1 1
2 3 4
5 6 6

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: