• mysql如何进行以,分割的字符串的拆分


    mysql如何进行以,分割的字符串的拆分

    现有如下需求:需要将字符串

    1,2,3,4,5,6,7

    拆分成

    1

    2

    3

    4

    5

    6

    7

    分析:

    为了完成上述功能,在MySQL中提供了一些字符串操作的函数,其中SUBSTRING_INDEX(str, delim, count)

    str: 要处理的字符串

    delim: 分割符

    count: 计数 如果为正数,则从左开始数,如果为负数,则从右开始数

    例:

    str = 'www.baidu.com';

    SELECT substring_index('www.baidu.com','.', 1);    #www
     
    SELECT substring_index('www.baidu.com','.', 2);    #www.baidu
     
    SELECT substring_index('www.baidu.com','.', -1);   #com
     
    SELECT substring_index('www.baidu.com','.', -2);   #baidu.com
     
    SELECT substring_index(substring_index('www.baidu.com','.', -2), '.', 1);  #baidu
     
    有了这个函数的帮助,我们还需要确定什么呢?需要知道  当前要分割的位置
    如何来获取当前要分割的位置呢?我们可以先获取总共能拆分成多少个字符串
    SELECT LENGTH('1,2,3,4,5,6,7') - LENGTH(REPLACE('1,2,3,4,5,6,7', ',', '')) + 1;
    结果为7,那么其实我们想要的就是遍历1到6,分别获取当前位置的字符串:SELECT substring_index(substring_index('1,2,3,4,5,6,7',',', index), ',', -1)
    其中index就是我们要遍历的位置,所以为了遍历,我们需要一个关联一个辅助表来得到当前位置,最后的设计如下:
     
    [sql] view plain copy
     
    1. SELECT substring_index(substring_index(t.context,',', b.help_topic_id + 1), ',', -1) FROM test.test t join mysql.help_topic b ON b.help_topic_id <  (LENGTH(t.context) - LENGTH(REPLACE(t.context, ',', '')) + 1);  

    其中表test数据如下:

    id context
    2 1,2,3,4,5,6,7

    这里使用到mysql的内置表help_topic_id,里面有508条数据(不同版本数据条数有差别),用户需要有对该表查询的权限才行,这样的话只满足分割数量少于508条的字符串,否则应该自定义辅助表,设置更大的一个递增列

  • 相关阅读:
    proxySql 报错connection is locked to hostgroup 100 but trying to reach hostgroup 200 解决办法
    构建harbor私有仓库
    Kubernetes Secret
    Kubernetes conifgMap
    kubernetes Ingress详解
    Kubernetes Service 详解
    RC、RS与Deployment的创建
    Pod的生命周期
    kubeadm安装Kubernetes单节点master集群
    App 需要的费用说明
  • 原文地址:https://www.cnblogs.com/handsome1013/p/7381918.html
Copyright © 2020-2023  润新知