In Java, we can use the split method of the String object to split a string into a string array by specified characters, but MySQL does not provide us with a string split function. Today we encountered this need in our work and found a solution. Share with everyone
Scenario: An organized table (the kind with a tree structure) has a field for tree-path that records the id of all parent departments of the current department. For example, 1-10-13 means that the parent organization of the organization is 13, 13 The parent organization of is 10, and the parent organization of 10 is 1. I query the organization structure of the current user. For example, the local machine of the Department of Transportation-the finance department-the person in charge of finance needs to split the tree-path and query it through in.
Solution one
1 Create a stored procedure
CREATE FUNCTION split(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
Function analysis: pass in three parameters, the first is the character to be divided, the second is the division by which, and the third parameter is the position of the divided area
2 Call the process to query
select split('1,2,3,4,5',',',help_topic_id)
from mysql.help_topic
where help_topic_id between 1 and length('1,2,3,4,5') -length(replace('1,2,3,4,5',',',''));
Analysis: Here is a table mysql.help_topic that comes with mysql. Its help_topic_id is continuous from 0 to 643, and then we only need to control the number of help_topic_id after the string is split.
Solution two
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('7654,7698,7782,7788',',',help_topic_id+1),',',-1) AS num
FROM
mysql.help_topic
WHERE
help_topic_id < LENGTH('7654,7698,7782,7788')-LENGTH(REPLACE('7654,7698,7782,7788',',',''))+1
Reference: https://www.cnblogs.com/gered/p/10797012.html