sql中拆分字段和合并字段
原sql

select arrchildid from sys_category where catid in ('120','1108')

查询结果:

arrchildid
120,140,141,143,144,145,147,149,1121
1108,1109,1110,1111,1112,1113,1114

1. 函数: group_concat(字段)

用来和并一个字段的所有行的值

sql

select group_concat(arrchildid) as arrchildid from sys_category where catid in ('120','1108')

查询结果:

arrchildid
120,140,141,143,144,145,147,149,1121,1108,1109,1110,1111,1112,1113,1114

2.函数 distinct 去重

substring_index 截取

select distinct substring_index(substring_index(a.arrchildid,',',b.help_topic_id+1),',',-1) as arrchildid
from sys_category as a join  mysql.help_topic b  on b.help_topic_id < (length(a.arrchildid) - length(replace(a.arrchildid,',',''))+1)
where a.catid in ('120','1108')

查询结果:

arrchildid
120
140
141
143
144
145
147
149
1121
1108
1109
1110
1111
1112
1113
1114

help_topic是mysql库下的一张表
使用help_topic时为了解决行转列的问题,出现上面错误是因为用户没有这张表的权限。

解决方法:
可以执行该SQL:GRANT SELECT ON mysql.help_topic TO 'autochain_uat'@'localhost'(给用户赋权限);
取消用户权限SQL:REVOKE SELECT ON mysql.help_topic FROM 'autochain_uat'@'localhost';

3.FIND_IN_SET(str,strlist)函数

str 要查询的字符串
strlist 字段名 参数以”,”分隔 如 (1,2,6,8)
查询字段(strlist)中包含(str)的结果,返回结果为null或记录
下面举例说明

Last modification:September 2, 2020
如果觉得我的文章对你有用,请随意赞赏