Oracle split split string, use of instr function

need:

The course field in the student table is the id of the course table: 1,2,3

Student table: student

………………
id name Course
1 card three 1, 2, 3

…………

Course Schedule: course

………………
     id name
     1 Language
     2 Number
     3 English
………………

When querying the student table, you need to associate the corresponding course name to find out, such as:

………………

Zhang San Chinese, Numbers, English

………………

 

Implementation scheme-1:

First, split the value of the student table course by comma; then use the function wm_concat to merge the columns of oracle.

 

An example of splitting using regular expressions:

--Example of splitting using regular expressions
SELECT REGEXP_SUBSTR ('abc1,cbd2,db3,db5', '[^,]+', 1,rownum) FROM DUAL
CONNECT BY ROWNUM <= LENGTH ('abc1,cbd2,db3,db5') - LENGTH (REPLACE ('abc1,cbd2,db3,db5', ',', ''))+1;

 accomplish:

select s.name
	,(
		select wm_concat(c.name)
		  from course c
		 where c.id in
			(
			 SELECT REGEXP_SUBSTR (s.course, '[^,]+', 1,rownum) as id FROM DUAL
			 CONNECT BY ROWNUM <= LENGTH (s.course) - LENGTH (REPLACE (s.course, ',', ''))+1
			)
	) as course
from student s
where s.name = 'Zhang San';

 

Implementation-2:

Use the instr function; then use the oracle merge column function wm_concat to merge.

select s.name
	,(
		select wm_concat(c.name)
		  from course c
		 where instr(s.course, c.id) > 0
	) as course
FROM student s where name ='张三';

 ***Disadvantage of this method : When course.id has a small value, it will be wrong.

    eg: student.course='12345,67890'  course.id=1

At this time, the record of course.id =1         will be wrongly checked out.

 

 

The instr function determines whether the source string ' contains the 'target string':

instr(sourceString,destString,start,appearPosition)

instr ('source string' , 'target string' , 'starting position', 'the first occurrence')

 

start represents the starting position of the search. This parameter is optional and defaults to 1. If the value of start is negative, it means the search is performed from right to left, but the position data is still calculated from left to right;

appearPosition represents the destString that you want to find the first occurrence of the source character. This parameter is also optional, and the default value is 1.

The return value is: the position of the found string.

The --instr function can be used instead of like. When searching for a large amount of data, the efficiency of instr is significantly higher than that of like.
instr('oracle','ac')>0 is equivalent to like '%ac%'
instr('oracle','ac')=0 is equivalent to not like '%ac%'

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326178951&siteId=291194637