先看一下数据结构,我这里字段比较少,只弄了最重要的部分

根据我们上次学到的left()函数进行分组

select left(provinces,6),count(1) from `region_map_copy` group by left(provinces,6)

得到的结果如下:

这样的效果并不是我们想要的,我们是要210000所有的都合并起来

使用substring_index(),left()这两个函数,在加help_topic这个表

help_topic:以字符拆分,一行转多行

select
 count(*),
  substring_index( substring_index( a.provinces, ',', b.help_topic_id + 1 ), ',',- 1 ) as ids 
 from
 `region_map_copy` as a
 join mysql.help_topic as b on b.help_topic_id < ( length( a.provinces ) - length( replace ( a.provinces, ',', '' ) ) + 1 )
 group by (substring_index( substring_index( a.provinces, ',', b.help_topic_id + 1 ), ',',- 1 )  )

结果如下:

得到了我们想要的

  • mysql 字段截取函数:
  • left(字段名,index) 从左边开始第index开始截取
  • right(字段名,index)从右边开始第index开始截取
  • substring(字段名,index)当index>0从左边开始截取直到结束 当index<0从右边开始截取直到结束 当index=0返回空
  • substring(字段名,index,len)从index开始,截取len长度
  • substring_index(字段名,str,count),str是截取的字段 count是从哪里开始截取(0从左边第0个开始,-1从右边第一个开始)

注意:这种方式不支持mariadb

补充:下面看下mysql数据库表中字段用逗号分隔,字段进行条件查询

select p.* from t_project_info p

select p.*
from t_project_info p
where  find_in_set(6,p.thematic_library_ids)

 

到此这篇关于mysql实现字段分割(一行转多行)的文章就介绍到这了,更多相关mysql字段分割内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!