Home Database Mysql Tutorial oralce函数substr和mysql函数substring_index初记

oralce函数substr和mysql函数substring_index初记

Jun 07, 2016 pm 04:23 PM
mysql substr function

oralce函数substr和mysql函数substring_index小记 ???? 最近偶尔在mysql数据库中看到了substring_index函数,先简单介绍下mysql的substring_index函数。??? substring_index(str,delim,count) 返回字符串str中在第 count 个出现的分隔符 delim之前的子串,和ja

oralce函数substr和mysql函数substring_index小记

???? 最近偶尔在mysql数据库中看到了substring_index函数,先简单介绍下mysql的substring_index函数。???

1

2

3

4

substring_index(str,delim,count) 返回字符串str中在第 count 个出现的分隔符 delim之前的子串,和java中的str.substring函数类似。

如果count是正数时候,substring_index是从左到右的顺序检查分隔符delim所在的位置。

如果count是负数时候,substring_index是从右到左的顺序检查分隔符delim所在的位置,返回的是从字符串str左边下标1开始的下标位置。

特殊点如果count等于0,那么,不管delim是否在str中存在,你得到的将是一个空白字符串。如下所示

Copy after login

???

1

2

select substring_index('www.baidu.com', '.', 0);

select substring_index('www.baidu.com', '-', 0);

Copy after login

??? 上面说的很抽象,来个简单的例子。

???

1

select substring_index('www.baidu.com', '.', 2);

Copy after login

?? 2为正数,.在str中存在,返回的结果是从下标1到第2次.出现的位置之间substr(1,10-1)的子串。所以结果是'www.baidu'。

??

1

select substring_index('www.baidu.com', '.', -2);

Copy after login

??? -2为负数,.在str中存在,.在str中搜索顺序是从右到左第2次出现的位置是4,用于是负数返回的是从最后到4+1的子串,也就是substr(str,4+1),所以结果是baidu.com。

??? 可以看到substring_index返回的子串是不包含分隔符 delim在str中第count次匹配的位置的,如果分隔符delim在str中出现的位置小于count次会发生什么呢?来测试下:

??

1

2

select substring_index('www.baidu.com', '.', 3);

select substring_index('www.baidu.com', '.', -3);

Copy after login

?? 运行之后可以看到返回的结果都是'www.baidu.com'。再来测试delim在str中不存在的情况:

??

1

2

select substring_index('www.baidu.com', '-', -1);

select substring_index('www.baidu.com', '-',1);

Copy after login

??? 运行之后可以看到返回的结果都是'www.baidu.com',从上面的测试可以知道分隔符delim在str中不存在或者出现次数小于指定的count时将返回str本身。上面只是测试了英文数据,中文数据测试也是一样的,测试如下:

??

1

2

3

4

select substring_index('我是中文_测试_数据','_',2) from dual;--我是中文_测试

select substring_index('我是中文_测试_数据','_',-2) from dual;--测试_数据

select substring_index('我是中文_测试_数据','_',0) from dual;--空白字符串

select substring_index('我是中文_测试_数据','_',3) from dual;--我是中文_测试_数据

Copy after login

??? 中英文混合的情况我就不测试了。

??? mysql有substring_index函数,oracle是否也要类似的函数呢?
我所知道的oracle中常见的只有substr和mysql的substring_index函数类似,有网友知道oralce其他函数的,麻烦留言告知。mysql中也有substr,关于两者的区别,后面我会简述。

??? 先简单的介绍下oracle的substr函数和instr函数,后面我会用这2个函数模拟mysql的substring_index函数

???

1

2

3

4

5

6

instr( string1, string2 [, start_position [, nth_appearance ] ] )

string1 源字符串

string2 目标字符串.

start_position 从string1 的哪个位置开始查找。默认为1. 字符串索引从1开始。为正,从左到右开始检索,为负,从右到左检索。

nth_appearance 代表要查找第几次出现的string2. 此参数可选,默认为 1.不能为负数

返回要查找的字符串string2在源字符串string1中的符合条件的开始索引

Copy after login

???

1

2

3

4

substr(string,start_position,length)

string 源字符串,即被截取的字符串.

start_position 字符截取的开始位置.start_position大于0时,从左边算起,小于0时,从右边查起

length 截取字符的个数.默认截取到最后一位.

Copy after login

??? 先来个测试:

???

1

select instr('www.baidu.com', '.',-1,2) from dual

Copy after login

??? .在str中存在,-1说明检索是从最后一位开始,2说明出现2次,返回的结果是4

??

1

select instr('www.baidu.com', '.',1,2) from dual

Copy after login

??? .在str中存在,1说明按从左到右的顺序,2说明出现2次,返回的结果是10

??? 下面来点特殊的测试,先测试nth_appearance,不是说不能为负数吗,我测试nth_appearance=0看下

???

1

2

select instr('www.baidu.com', '.',1,0) from dual

select instr('www.baidu.com', '.',-1,0) from dual

Copy after login

??? 你们猜结果是什么?结果是ORA-01428:参数'0'超出范围,说明nth_appearance不能为0,只能大于0。

??? 再测试start_position,令start_position=0看下

???

1

2

3

4

select instr('www.baidu.com', '.',0,1) from dual

select instr('www.baidu.com', '-',0,1) from dual

select instr('www.baidu.com', '.',0,2) from dual

select instr('www.baidu.com', '-',0,2) from dual

Copy after login

??? 测试结果都是0;如果把start_position改为>0,结果如下

???

1

2

3

4

select instr('www.baidu.com', '.',1,1) from dual--4

select instr('www.baidu.com', '-',1,1) from dual--0

select instr('www.baidu.com', '.',1,2) from dual--10

select instr('www.baidu.com', '-',1,2) from dual--0

Copy after login

??? 如果把start_position改为<0,结果如下:

???

1

2

3

4

5

6

7

8

select instr('www.baidu.com', '.',-1,1) from dual--10

select instr('www.baidu.com', '-',-1,1) from dual--0

select instr('www.baidu.com', '.',-1,2) from dual--4

select instr('www.baidu.com', '-',-1,2) from dual--0

select instr('www.baidu.com', '.',-1,3) from dual--0

select instr('www.baidu.com', '-',-1,3) from dual--0

select instr('www.baidu.com', '.',-1,3) from dual--0

select instr('www.baidu.com', '-',-1,3) from dual--0

Copy after login

??? 可以看出instr函数目标字符串在str中不存在时候或者出现次数小于给定的次数时,返回的都是0;

??? 使用中文测试也是一样:

???

1

2

3

4

5

select instr('我是中文_测试_数据','_',1,0) from dual;--ORA-01428:参数'0'超出范围

select instr('我是中文_测试_数据','_',1,2) from dual;--8

select instr('我是中文_测试_数据','_',1,3) from dual;--0

select instr('我是中文_测试_数据','_',-1,2) from dual;--5

select instr('我是中文_测试_数据','_',-1,3) from dual;--0

Copy after login

??? 下面测试下substr。

???

1

2

select substr('www.baidu.com',0,4) from dual

select substr('www.baidu.com',1,4) from dual

Copy after login

??? 上面2个执行结果都是'www.'。如果上面是在mysql下测试,结果如下:

???

1

2

select substr('www.baidu.com',0,4) from dual--空白字符串

select substr('www.baidu.com',1,4) from dual--www.

Copy after login

??? 从这里可以看出mysql中substr开始位置不能为0,而oracle下从0开始或者从1开始结果是一样的,下面继续oracle测试。

??

1

2

select substr('www.baidu.com',1) from dual

select substr('www.baidu.com',1,22) from dual

Copy after login

??? 返回结果是'www.baidu.com'。

??

1

2

3

select substr('www.baidu.com',-1) from dual

select substr('www.baidu.com',-1,4) from dual

select substr('www.baidu.com',-1,22) from dual

Copy after login

??? 返回的结果是'm',说明substr返回的是从开始位置到str最后一位。

??? 使用中文测试如下:

???

1

2

3

4

5

select substr('我是中文_测试_数据',1) from dual--我是中文_测试_数据

select substr('我是中文_测试_数据',1,22) from dual--我是中文_测试_数据

select substr('我是中文_测试_数据',-1) from dual--据

select substr('我是中文_测试_数据',-1,4) from dual--据

select substr('我是中文_测试_数据',-1,22) from dual--据

Copy after login

??? 从上面的测试可以看出oracle下instr函数和mysql的substring_index函数很像,instr函数已经可以得到下标了,结合substr可以截取子串返回。

??? Mysql的

???

1

select substring_index('www.baidu.com', '.', 2);

Copy after login

??? Oralce可以这样做:

???

1

select substr('www.baidu.com', 1, instr('www.baidu.com', '.',1,2)-1) from dual

Copy after login

??? instr函数再-1是因为mysqlsubstring_index返回结果不包括.,上面返回的结果都是'www.baidu'。

???

??? Mysql的

???

1

select substring_index('www.baidu.com', '.', -2);

Copy after login

??? Oracle可以这样做:

???

1

2

select substr('www.baidu.com', instr('www.baidu.com', '.',-1,2) + 1, length('www.baidu.com'))from dual

select substr('www.baidu.com', instr('www.baidu.com', '.',-1,2) + 1) from dual

Copy after login

??? 上面可以不使用length函数,因为oracle的substr默认截取到str最后一位。

???? 中文测试如下:
???? Mysql下面:

????

1

2

3

4

5

6

select substring_index('我是中文_测试_数据','_',1) from dual;--我是中文

select substring_index('我是中文_测试_数据','_',2) from dual;--我是中文_测试

select substring_index('我是中文_测试_数据','_',-2) from dual;--测试_数据

select substring_index('我是中文_测试_数据','_',0) from dual;--空白字符串

select substring_index('我是中文_测试_数据','_',3) from dual;--我是中文_测试_数据

select substring_index('我是中文_测试_数据','.',3) from dual;--我是中文_测试_数据

Copy after login

??? Oracle下面:

???

1

2

3

4

5

6

select substr('我是中文_测试_数据', 1, instr('我是中文_测试_数据', '_',1,1)-1) from dual--我是中文

select substr('我是中文_测试_数据', 1, instr('我是中文_测试_数据', '_',1,2)-1) from dual--我是中文_测试

select substr('我是中文_测试_数据', instr('我是中文_测试_数据', '_',-1,2) + 1) from dual--测试_数据

select substr('我是中文_测试_数据', 1, instr('我是中文_测试_数据', '_',1,0)-1) from dual--ORA-01428:参数'0'超出范围

select substr('我是中文_测试_数据', 1, instr('我是中文_测试_数据', '_',1,3)-1) from dual--空白

select substr('我是中文_测试_数据', 1, instr('我是中文_测试_数据', '.',1,3)-1) from dual--空白

Copy after login

??? 可以看到我写的这个有点问题,如果想在nth_appearance(>0)大于目标串在str中出现的次数时和mysql一样返回整个字符串,可以这样写:

???

1

2

3

4

5

6

7

8

9

10

select substr('我是中文_测试_数据',

             1,

             (select (case

                       when instr('我是中文_测试_数据', '_', 1, 3) <= 1 then

                        (select length('我是中文_测试_数据') from dual)

                       else

                        (instr('我是中文_测试_数据', '_', 1, 3) - 1)

                     end)

                from dual))

 from dual

Copy after login

??? 这个在nth_appearance=0时用不了,进一步,考虑到nth_appearance=0时候返回NULL可以这样做,返回''这样的字符串使用substr做不了。

???

1

2

3

4

5

6

7

8

9

10

11

12

13

14

select substr('我是中文_测试_数据',

                1,

                (select (case

                          when 0 = 0 then

                           -1

                          else

                           case

                          when instr('我是中文_测试_数据', '_', 1, 3) <= 1 then

                           (select length('我是中文_测试_数据') from dual)

                          else

                           (instr('我是中文_测试_数据', '_', 1, 3) - 1)

                        end end)

                   from dual))

    from dual

Copy after login

??? 上面的sql是不是很丑陋,,我们可以定义一个存储过程封装一下。

????

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

create or replace procedure my_substring_index(str      in varchar2,

                                               delim    in varchar2,

                                               in_count in int,

                                               out_str  out varchar2) as

  v_time  int;

  v_delim varchar2(20);

begin

  if str is null then

    out_str := '空白字符串';

  elsif length(str) = 0 then

    out_str := '空白字符串';

  end if;

 

  if delim is null then

    v_delim := ' ';

  elsif length(delim) = 0 then

    v_delim := ' ';

  else

    v_delim := delim;

  end if;

 

  if in_count = 0 then

    out_str := '空白字符串';

  elsif in_count>0 then

   v_time := instr(str, delim, 1, in_count);

  else

   v_time := instr(str, delim, -1, (-1)*in_count);

  end if;

   

 

  if v_time = 0 then

    out_str := str;

  end if;

   

  if in_count>0  then

    if v_time = 1 then

      out_str := '空白字符串';

    elsif v_time > 1 then

      select substr(str, 1, v_time - 1) into out_str from dual;

    end if;

  elsif in_count<0 then

    if v_time >= 1 then

     select substr(str, v_time + 1) into out_str from dual;

     end if;

  end if;

end my_substring_index;

Copy after login

?? Oracle上面测试过程如下:

??? 在My Object下面的Procedures下找到存储过程my_substring_index,点击右键选择Test.出来Oracle的测试脚本:

???

1

2

3

4

5

6

7

begin

  -- Call the procedure

  my_substring_index(str => :str,

                     delim => :delim,

                     in_count => :in_count,

                     out_str => :out_str);

end;

Copy after login

?? 在测试脚本页面下面填上具体值,按F8,不出意外的化可以看到返回值。

?? 如果想自己写脚本可以这样,新建一个sql文件,内容如下:

??

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

declare

   v_str varchar2(50);

   v_delim varchar2(20);

   v_in_count number;

   v_out_str varchar2(20);

begin

  v_str:='&str';

  v_delim:='&delim';

  v_in_count:=&in_count;

  my_substring_index(str => v_str,

                     delim => v_delim,

                     in_count => v_in_count,

                     out_str => v_out_str);

  dbms_output.put_line('result='||v_out_str);

end;

Copy after login

??? 在命令行下运行:

???

1

2

3

4

5

6

SQL> set serveroutput on;

SQL> start f:/saveFile/test.sql

 16  /

  

result=www.baidu

PL/SQL procedure successfully completed

Copy after login

??? 如果想直接在cmd window下测试,可以这样:

???

1

2

3

4

5

6

7

8

9

10

SQL> set serveroutput on;

SQL> var v_str varchar2(50);

SQL> var v_delim varchar2(20);

SQL> var v_in_count number;

SQL> var v_out_str varchar2(50);

SQL> exec :v_str:='我是中文_测试_数据';

SQL> exec :v_delim:='_';

SQL> exec :v_in_count:=2;

SQL> exec my_substring_index(:v_str,:v_delim,:v_in_count,:v_out_str);

SQL> print v_out_str;

Copy after login

????? 以上是我写的oralce函数substr和mysql函数substring_index简单介绍,文章有点简单,但毕竟是原创,转载请注明出处。
????? 全文完,写的不好的地方请见谅,大神请绕过。

?

?

?

?

?

?

?

?

?

?

?

?

??

????

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

See all articles