zoukankan      html  css  js  c++  java
  • [转]Mysql字符串截取总结:left()、right()、substring()、substring

    同步首发https://yuanrengu.com/2020/9cfe2ad6.html

    在实际的项目开发中有时会有对数据库某字段截取部分的需求,这种场景有时直接通过数据库操作来实现比通过代码实现要更方便快捷些,mysql有很多字符串函数可以用来处理这些需求,如Mysql字符串截取总结:left()、right()、substring()、substring_index()。

    一.从开始截取字符串

    用法:left(str, length),即:left(被截取字符串, 截取长度)

    SELECT LEFT('www.yuanrengu.com',8)

    结果为:www.yuan

    二.从开始截取字符串

    用法:right(str, length),即:right(被截取字符串, 截取长度)

    SELECT RIGHT('www.yuanrengu.com',6)

    结果为:gu.com

    三.截取特定长度的字符串

    用法:

    • substring(str, pos),即:substring(被截取字符串, 从第几位开始截取)
    • substring(str, pos, length),即:substring(被截取字符串,从第几位开始截取,截取长度)

    1.从字符串的第9个字符开始读取直至结束

    SELECT SUBSTRING('www.yuanrengu.com', 9)

    结果为:rengu.com

    2.从字符串的第9个字符开始,只取3个字符

    SELECT SUBSTRING('www.yuanrengu.com', 9, 3)

    结果为:ren
    3.从字符串的倒数第6个字符开始读取直至结束

    SELECT SUBSTRING('www.yuanrengu.com', -6)

    结果为:gu.com

    4.从字符串的倒数第6个字符开始读取,只取2个字符

    SELECT SUBSTRING('www.yuanrengu.com', -6, 2)

    结果为:gu

    四.按关键字进行读取

    用法:substring_index(str, delim, count),即:substring_index(被截取字符串,关键字,关键字出现的次数)

    1.截取第二个“.”之的所有字符

    SELECT SUBSTRING_INDEX('www.yuanrengu.com', '.', 2);

    结果为:www.yuanrengu

    2.截取倒数第二个“.”之的所有字符

    SELECT SUBSTRING_INDEX('www.yuanrengu.com', '.', -2);

    结果为:yuanrengu.com

    3.如果关键字不存在,则返回整个字符串

    SELECT SUBSTRING_INDEX('www.yuanrengu.com', 'sprite', 1);

    结果为:www.yuanrengu.com


    ---------------------
    作者:猿人谷
    来源:CNBLOGS
    原文:https://www.cnblogs.com/heyonggang/p/8117754.html
    版权声明:本文为作者原创文章,转载请附上博文链接!
    内容解析By:CSDN,CNBLOG博客文章一键转载插件

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/rensi/p/14626444.html
Copyright © 2011-2022 走看看